如何在C/C++中获取函数的执行时间

How to obtain the execution time of a function in C/C++

本文关键字:获取 函数 执行时间 C++      更新时间:2023-10-16

我有一个函数,可以生成10000个随机数并将其写入文件。

void generator(char filename[])              
{
    int i;
    int n;
    FILE* fp;
    if((fp=fopen(filename,"w+"))==NULL)
    {
        printf("Fail creating file!");
    }
    srand((unsigned)time(NULL));
    for(i=0;i<10000;i++)
    {
        n=rand()%10000;
        fprintf(fp,"%d ",n);
    }
    fclose(fp);
}

如何使用C/C++获取此函数的执行时间?

代码分析不是一项特别容易的任务(或者,正如我们在编程中经常说的那样,它是"非平凡的"。)问题是因为以秒为单位的"执行时间"不是特别准确或有用。

您想要做的是测量CPU周期数。这可以使用外部工具来完成,例如callgrind(Valgrind的工具之一)。99%的可能性就是你想要的。

如果你真的想在代码中自己做到这一点,那么你正在承担一项相当困难的任务。我第一手就知道了——我用C++编写了一个比较基准库,用于动态性能测试。

如果你真的想走这条路,你可以研究英特尔处理器(主要是AMD)的基准测试,或者你使用的任何处理器。然而,正如我所说,这个主题是庞大而深入的,远远超出了StackOverflow答案的范围。

您可以使用chrono库;

#include <chrono>
//*****//
auto start = std::chrono::steady_clock::now();
generator("file.txt")
auto end = std::chrono::steady_clock::now();
std::cout << "genarator() took "
              << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << "us.n";

您已经有了一些同样适用于C++的C答案
这里是一个使用<chrono>的原生C++解决方案:

auto tbegin = std::chrono::high_resolution_clock::now(); 
...
auto tend = std::chrono::high_resolution_clock::now();
auto tduration = std::chrono::duration_cast<std::chrono::microseconds>(tend - tbegin).count();

优点是您可以很容易地从microsecond切换到millisecondseconds或任何其他时间测量单位。

请注意,您可能对时钟精度有操作系统限制(在windows环境中通常为15毫秒),因此只有当您确实高于此限制时,这可能会产生有意义的结果。

void generator(char filename)
{
    clock_t tStart = clock();
    /* your code here */
    printf("Time taken: %.2fsn", (double)(clock() - tStart)/CLOCKS_PER_SEC);
}
upd. And add #include <ctime>

试试这个

    #include <sys/time.h> 
    struct timeval tpstart,tpend; 
    double timeuse; 
    //get time before generator starts
    gettimeofday(&tpstart,NULL); 
    //call generator function
    generator(filename);
    //get time after generator ends
    gettimeofday(&tpend,NULL); 
    //calculate the used time
    timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec; 
    timeuse/=1000000; 
    printf("Used Time:%fsecn",timeuse);
#include <ctime>
 .....
clock_t start = clock();
...//the code you want to get the execution time for
double elapsed_time = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;
std::cout << elapsed_time << std::endl;//elapsed_time now contains the execution time(in seconds) of the code in between

将为您提供第一次和第二次clock()调用之间代码的大致(不准确)执行时间

暂时将限额设为10000000

用秒表计时。将时间除以1000