我有一个问题,我想测量函数的时间。我在函数的开头和结尾调用计时器,但即使当我调用 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。
谢谢,最诚挚的问候 阿明
最佳答案
因为时间不一定能给出毫秒分辨率。它以“CLK_TCK 秒”为增量给出时间
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.
所以它与我习惯使用的挂钟式计时不同。在调用 times
之间,该进程必须主动运行(而不是休眠)超过 1/CLK_TCK
秒,然后您才会看到它滴答作响。
关于c - 为什么在 C 中 sleep(5) 之后 times 给我相同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26640819/