在整个程序的执行上测量运行时很少用于高分辨率; 在分析事物时,通常不希望包含太多的开销.
通常最好只测量一些关键路径的执行时间,即使这样,重复多次执行该路径通常也是一个好主意,以提高时序精度.
在Linux/POSIX系统下,gettimeofday()
经常用于这种时序,它具有微秒精度:
#include <sys/time.h>
#include <time.h>
#include <stdio.h>
int main(void)
{
struct timeval then, now;
int i;
gettimeofday(&then, NULL);
for(i = 0; i < 100000; i++)
my_interesting_function();
gettimeofday(&now, NULL);
printf("Did %d executions in %.3g seconds\n", i, now.tv_sec - then.tv_sec + 1e-6 * (now.tv_usec - then.tv_usec));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
以上假设这my_interesting_function()
是您要测量其性能的函数.当然,根据函数的实际运行时间调整重复次数.