首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么时间给我同样的输出后睡眠(5)C

为什么时间给我同样的输出后睡眠(5)C
EN

Stack Overflow用户
提问于 2014-10-29 21:15:21
回答 1查看 106关注 0票数 0

我有一个问题,我想测量一个函数的时间。我在函数的开头和结尾调用计时器,但是它返回相同的值,即使我调用睡眠(5)。

在这里,代码:

代码语言:javascript
复制
#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。

谢谢,代我问候阿明

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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字段列出如下:

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26640819

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档