c - 为什么在 C 中 sleep(5) 之后 times 给我相同的输出

标签 c timer sleep

我有一个问题,我想测量函数的时间。我在函数的开头和结尾调用计时器,但即使当我调用 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/

相关文章:

iPhone - 区分 UIApplicationDidBecomeActiveNotification 通知

C11 VLA 矩阵访问

c - 赋值从指针生成整数,无需在 C 中进行强制转换

c - 编译器如何以及为什么将 extern 函数替换为空函数?

linux - 内核模块使用周期性内核定时器(jiffies 或 hrtimer)从 UART 收集数据

如果线程生成速度过快,Ruby 工作分配会失败

linux - 系统启动后应用程序自动启动 Linux 中的随机时间间隔

c - 偏离说明,有趣但信息丰富的结构练习

javascript - HighCharts-ng 的 Angular JS 中的 setInterval 不起作用

java - 如何在一天后自动终止计时器?