如何在C/C++中获取函数的执行时间
How to obtain the execution time of a function in C/C++
我有一个函数,可以生成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
切换到millisecond
、seconds
或任何其他时间测量单位。
请注意,您可能对时钟精度有操作系统限制(在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
相关文章:
- 具有默认值的引用获取函数
- 如何从"decltype()"获取函数参数的数量<funtion>?
- C++ 获取函数在常量引用中按值返回的结果
- 如何从参数中获取函数签名?
- 获取函数的地址?
- 如何从不同的类中获取函数来调用在 Main 中声明的对象?
- 在 gcc/clang (C++) 中获取函数范围之外的标签地址
- 如何使用 std::invoke_result_t 获取函数的返回类型
- 获取函数中基元类型的指针
- 如何从 lambda 表达式中获取函数指针?
- 如何从核密度估计中获取函数?
- 如何在函数内部使用 zmq(以非阻塞方式)在客户端请求时获取函数的状态?
- 具有获取函数的无限循环
- 使用 decltype(this) 获取函数引用
- 在编译时使用可变参数模板在 c++ 中使用参数类型检查获取函数的参数数
- 如何在C++中接收任何类型的函数参数并获取函数内传递变量的类型?
- 从C 中的PHP扩展中获取函数参数值
- 从返回绑定中获取函数失败
- 从 Rcpp c++ 函数获取 r 函数参数
- 获取函数调用方的地址?