为什么在C睡眠后(5)给我输出相同的输出?

为什么在C睡眠后(5)给我输出相同的输出?

问题描述:

我有一个问题,我想测量一个函数的时间。我在函数的开头和结尾调用了定时器,但即使在我调用sleep(5)时它也会返回相同的值。为什么在C睡眠后(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); 

} 

请注意,我必须使用定时器功能。 我正在使用MAC OS X 10.10并且在MacBook Pro的虚拟机Ubuntu 14.04上。

感谢,问候 阿明

+0

与测试函数的运行时间相比,您正在使用的计时器函数的粒度是多少? – 2014-10-29 21:22:38

+2

因为在代码睡着时,系统或用户空间中都没有使用CPU。 – 2014-10-29 21:25:55

+0

好的,谢谢你指出这一点。当我在function_to_time中使用while循环时,我遇到了同样的问题。这应该花费用户时间? – Armin 2014-10-30 12:50:39

由于时间不一定能给出毫秒。它给次的“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秒,然后才能看到它。

+0

所以这个函数必须执行一秒以上? – Armin 2014-10-30 12:52:07

+0

真的那个功能消耗的时间太少了。谢谢! – Armin 2014-10-31 06:02:05