C++加法与乘法耗时问题

一般来说,乘法是比加法耗的时间更多,但是在一次写c++时想减少乘法次数而多次调用函数,导致最后测试运行时间增加,不过偶然发现似乎乘法与加法耗时差不多,于是写了简单的测试样例,这个问题待考究。


测试代码

#include <iostream>
using namespace std;

void Test1(int n){
    int k=0;
    for(int i=0;i<n;i++){
        k+=i;
    }
}

void Test2(int n){
    int a=1;
    for(int i=1;i<n;i++){
        a=a*i;
    }
}

void Test3(int n){
    int a=10000000;
    for(int i=1;i<n;i++){
        int ans=a/i;
    }
}

void Test4(int n){
    if(n<0)
        return;
    Test4(n-1);
}

int main() {
    clock_t start,finish;
    double totaltime;
    start=clock();
    Test1(100000);
    finish=clock();
    totaltime=(double)(finish-start);
    cout<<"\n加法程序的运行时间为"<<totaltime<<"秒!"<<endl;
    start=clock();
    Test2(100000);
    finish=clock();
    totaltime=(double)(finish-start);
    cout<<"\n乘法程序的运行时间为"<<totaltime<<"秒!"<<endl;
    start=clock();
    Test3(100000);
    finish=clock();
    totaltime=(double)(finish-start);
    cout<<"\n除法程序的运行时间为"<<totaltime<<"秒!"<<endl;
    start=clock();
    Test4(100000);
    finish=clock();
    totaltime=(double)(finish-start);
    cout<<"\n函数调用程序的运行时间为"<<totaltime<<"秒!"<<endl;
}

结果是:

加法程序的运行时间为336秒!

乘法程序的运行时间为319秒!

除法程序的运行时间为296秒!

函数调用程序的运行时间为2759秒!

在C++下似乎函数调用的耗时最多,加法乘法以及除法的耗时接近,这可能跟cpu厂商的优化有关系。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容