我有问题,我想测量一个功能的时间。我在函数的开头和结尾调用timer,但即使我调用sleep(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);
}
请注意我必须使用计时器功能。 我在MacBook Pro上使用MAC OS X 10.10和虚拟机Ubuntu 14.04。
谢谢,最诚挚的问候 阿明
答案 0 :(得分:0)
因为时间不一定能提供毫秒级的分辨率。它以&#34; CLK_TCK为秒的增量给出时间&#34;
https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/times.3.html
编辑:
@Armin,该函数必须运行超过1/CLK_TCK
秒。但仔细观察后,我认为@JonathanLeffler说得更对。返回的结构字段直接应用于调用进程列为:
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.
所以它与我以前使用的挂钟式时序不同。在您看到它之前,该过程必须在调用1/CLK_TCK
之间超过times
秒的时间内主动运行(而不是休眠)。