我有一个问题,我想测量一个函数的时间。我在函数的开头和结尾调用计时器,但是它返回相同的值,即使我调用睡眠(5)。
在这里,代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/times.h>
void function_to_time(void);
int main(void) {
double clockticks, cticks;
clock_t tcend, tcstart;
struct tms tmend, tmstart;
if ((clockticks = (double) sysconf(_SC_CLK_TCK)) == -1) {
perror("Failed to determine clock ticks per second");
return 1;
}
printf("The number of ticks per second is %f\n", clockticks);
if (clockticks == 0) {
fprintf(stderr, "The number of ticks per second is invalid\n");
return 1;
}
if ((tcstart = times(&tmstart)) == -1) {
perror("Failed to get start time");
return 1;
}
function_to_time();
if ((tcend = times(&tmend)) == -1) {
perror("Failed to get end times");
return 1;
}
cticks = tmend.tms_utime + tmend.tms_stime
- tmstart.tms_utime - tmstart.tms_stime;
printf("Total CPU time for operation is %f seconds\n", cticks/clockticks);
if ((tcend <= tcstart) || (tcend < 0) || (tcstart < 0)) {
fprintf(stderr, "Tick time wrapped, couldn't calculate fraction\n");
return 1;
}
printf("Fraction of CPU time used is %f\n", cticks/(tcend - tcstart));
return 0;
}
void function_to_time()
{
sleep(5);
}请注意,我必须使用计时器功能。我使用的是MacOSX10.10和MacBook Pro上的一个虚拟机Ubuntu14.04。
谢谢,代我问候阿明
发布于 2014-10-29 21:23:35
因为时间不一定能给毫秒的分辨率。它给出"CLK_TCK's‘s“的递增次数。
https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/times.3.html
编辑:
@Armin,函数的运行时间必须超过1/CLK_TCK秒。但经过仔细观察,我认为约拿珊·莱弗勒(JonathanLeffler)的观点更为正确。直接应用于调用进程的struct字段列出如下:
tms_utime //The CPU time charged for the execution of user instructions.
tms_stime //The CPU time charged for execution by the system on behalf of the process.所以它不同于我习惯使用的挂钟式的计时方式。进程必须在对times的调用之间运行(而不是休眠)超过1/CLK_TCK秒,然后才能看到它的滴答声。
https://stackoverflow.com/questions/26640819
复制相似问题