我需要一个工具来测量程序的运行时间,比如gprof。但是gprof的分辨率还不够好(约0.01秒)。 oprofile似乎可以做到,我会尝试学习如何获取有关时间信息的数据,但我不能。
那么,谁可以告诉我如何做到的步骤,或者任何人都知道其他工具可以做同样的事情?
答案 0 :(得分:6)
测量整个程序的运行时间执行很少用于高分辨率;在分析事物时,通常不希望包含太多的开销。
通常最好只测量一些关键路径的执行时间,即使这样,多次重复执行该路径通常也是一个好主意,以提高计时准确性。
在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;
}
以上假设my_interesting_function()
是您要测量其性能的函数。当然,根据函数的实际运行时间调整重复次数。
答案 1 :(得分:2)
即使这是一篇旧文章,我还是认为我会发布一些代码,我认为这些代码对于测量流程的运行时非常有用,因为它可能对其他人有用。
#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;
}
可以轻松扩展代码以利用其他整洁的东西提供的优势(有关详细信息,请参阅http://www.gnu.org/s/libc/manual/html_node/Resource-Usage.html)。希望有人会发现它有用:)
此致 瓦西尔
答案 2 :(得分:0)
如果您使用的是Linux / MacOSX / Unix,则可以始终使用time
命令。
即使在超级计算机上也相当准确。时间以秒为单位记录,精确到3位数(即:1.034s)。唯一的问题是它将测量应用程序的整个运行时间,您无法仅测量子例程。
示例用法:
time ./myApplication
否则你将不得不写一个计时器类。
答案 3 :(得分:0)
如果您只想计时,请将其重复10 ^ 3或10 ^ 6次,如放松所说,然后秒表。 (我真的用我的手表。)
如果你想知道什么使它变慢(一个非常不同的问题),你可以比gprof做得更好。 Try this. If you're interested, here's a critique of gprof.