【发布时间】:2010-02-04 09:41:14
【问题描述】:
我需要一个工具来测量程序的运行时间,比如 gprof。但是gprof的分辨率不够好(0.01秒左右)。 oprofile似乎可以做到,我会尝试学习如何获取有关时间信息的数据,但我做不到。
那么,谁能告诉我如何做的步骤,或者谁知道其他工具可以做同样的事情?
【问题讨论】:
标签: profiler
我需要一个工具来测量程序的运行时间,比如 gprof。但是gprof的分辨率不够好(0.01秒左右)。 oprofile似乎可以做到,我会尝试学习如何获取有关时间信息的数据,但我做不到。
那么,谁能告诉我如何做的步骤,或者谁知道其他工具可以做同样的事情?
【问题讨论】:
标签: profiler
测量整个程序执行的运行时间在高分辨率下很少有用;在分析事物时通常不想包含太多开销。
通常最好只测量某些关键路径的执行时间,即使这样,重复执行该路径多次以提高时序准确性通常也是一个好主意。
在Linux/POSIX系统下,@987654321@经常用于这样的计时,它有微秒级的精度:
#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() 是您要测量其性能的函数。当然可以根据函数的实际运行时间来调整重复次数。
【讨论】:
尽管这是一篇旧帖子,但我想我会发布一些我认为对于衡量进程的运行时间非常有用的代码,因为它可能对其他人有用。
#include <sys/time.h>
#include <sys/resource.h>
typedef struct tag_time_measure
{
struct timeval startTimeVal;
struct timeval stopTimeVal;
struct rusage startTimeUsage;
struct rusage stopTimeUsage;
} time_measure;
time_measure * startTimeMeasuring()
{
time_measure * tu = malloc(sizeof(time_measure));
if(!tu)
exit(1);
getrusage(RUSAGE_SELF, &tu->startTimeUsage);
gettimeofday(&tu->startTimeVal,0);
return tu;
}
void stopTimeMeasuring(time_measure * tu)
{
getrusage(RUSAGE_SELF, &tu->stopTimeUsage);
gettimeofday(&tu->stopTimeVal,0);
}
void printMeasuredTime(time_measure * tu)
{
struct timeval elapsedVal;
struct timeval userVal;
struct timeval systemVal;
double elapsed_millis = 0.0f;
double user_millis = 0.0f;
double system_millis = 0.0f;
timersub(&tu->stopTimeVal, &tu->startTimeVal, &elapsedVal);
timersub(&tu->stopTimeUsage.ru_utime, &tu->startTimeUsage.ru_utime, &userVal);
timersub(&tu->stopTimeUsage.ru_stime, &tu->startTimeUsage.ru_stime, &systemVal);
elapsed_millis = elapsedVal.tv_sec * 1000 + (double) elapsedVal.tv_usec / 1000;
user_millis = userVal.tv_sec * 1000 + (double) userVal.tv_usec / 1000;
system_millis = systemVal.tv_sec * 1000 + (double) systemVal.tv_usec / 1000;
printf("\n\n---Program execution times in milliseconds--- \n");
printf("Total:\t\t %f\nUser:\t\t %f\nSystem:\t\t %f\n", elapsed_millis, user_millis, system_millis);
}
然后可以使用以下功能:
int main(void)
{
time_measure * tu = startTimeMeasuring();
doSomethingExpensiveHere();
stopTimeMeasuring(tu);
printMeasuredTime(tu);
free(tu);
return EXIT_SUCCESS;
}
代码可以很容易地扩展以利用 rusage 提供的其他简洁的东西(有关更多详细信息,请参阅http://www.gnu.org/s/libc/manual/html_node/Resource-Usage.html)。希望有人会发现这很有用:)
问候, 瓦西尔
【讨论】:
startTimeMeasuring() 函数的 malloc 前面添加一个演员表。
如果您使用的是 Linux/MacOSX/Unix,您始终可以使用time 命令。
即使在超级计算机上也相当准确。时间以秒为单位记录,精确到 3 位数(即:1.034 秒)。唯一的问题是它将测量应用程序的整个运行时间,您不能只测量子例程。
示例用法:
time ./myApplication
否则你将不得不编写一个计时器类。
【讨论】:
如果您只是想计时,请按照 unwind 所说的那样迭代 10^3 或 10^6 次,然后秒表。 (我真的用我的手表。)
如果您想找出导致它变慢的原因(一个非常不同的问题),您可以比 gprof 做得更好。 Try this. If you're interested, here's a critique of gprof.
【讨论】: