问题描述
我需要一个工具来测量程序的运行时间,比如 gprof.但是gprof的分辨率不够好(约0.01秒).oprofile 似乎可以做到,我将尝试学习如何获取有关时间信息的数据,但我不能.
I need a tool to measure a program's running time, like gprof. But the resolution of gprof is not good enough (about 0.01 second). oprofile seems can do it, I will try to learn how to get the data about the time info, but I can't.
那么,谁能告诉我怎么做的步骤,或者谁知道其他工具可以做同样的事情?
So, who can tell me the steps how to do it, or anyone knows other tool can do the same thing?
推荐答案
在高分辨率下测量整个程序执行的运行时间很少有用;在分析事物时,您通常不想包含太多的开销.
Measuring runtime over a whole program's execution is seldom useful with high resolution; there's too much overhead that you generally don't want to include when you're profiling things.
通常最好仅测量某些关键路径的执行时间,即使如此,多次重复执行该路径通常也是一个好主意,以提高计时准确性.
It's often better to measure the execution time of some critical path only, and even then it's often a good idea to repeat the execution of that path many times, to improve timing accuracy.
在 Linux/POSIX 系统下,gettimeofday()
通常用于这种计时,它具有微秒级精度:
Under Linux/POSIX systems, gettimeofday()
is often used for such timing, it has microsecond precision:
#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;
}
以上假设 my_interesting_function()
是您要测量其性能的函数.当然根据函数的实际运行时间调整重复次数.
The above assumes that my_interesting_function()
is the function whose performance you want to measure. Of course tweak the number of repetitions depending on the actual runtime of the function.
这篇关于测量程序的运行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!