我使用的是64位Ubuntu 12.04系统,并尝试了以下代码:
#include <unistd.h>
#include <time.h>
#include <stdio.h>
int
main(void)
{
struct timespec user1,user2;
struct timespec sys1,sys2;
double user_elapsed;
double sys_elapsed;
clock_gettime(CLOCK_REALTIME, &user1);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &sys1);
sleep(10);
clock_gettime(CLOCK_REALTIME, &user2);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &sys2);
user_elapsed = user2.tv_sec + user2.tv_nsec/1E9;
user_elapsed -= user1.tv_sec + user1.tv_nsec/1E9;
printf("CLOCK_REALTIME: %f\n", user_elapsed);
sys_elapsed = sys2.tv_sec + sys2.tv_nsec/1E9;
sys_elapsed -= sys1.tv_sec + sys1.tv_nsec/1E9;
printf("CLOCK_PROCESS_CPUTIME_ID: %f\n", sys_elapsed);
}
据我了解,这应该打印类似
CLOCK_REALTIME: 10.000117
CLOCK_PROCESS_CPUTIME_ID: 10.001
但就我而言,我得到的是
CLOCK_REALTIME: 10.000117
CLOCK_PROCESS_CPUTIME_ID: 0.000032
这是正确的行为吗?如果是这样,我如何确定sys1和sys2的实际秒数?
当我将CLOCK_PROCESS_CPUTIME_ID更改为CLOCK_REALTIME时,我得到了预期的结果,但这不是我想要的,因为我们需要精度。
[EDIT]显然,CLOCK_PROCESS_CPUTIME_ID返回CPU在处理过程上花费的实际时间。 CLOCK_MONOTONIC似乎返回正确的值。但是,精确度是多少?
最佳答案
如果我不误会的话,这里的运行时间是指耗时。通常,CLOCK_REALTIME
对此很有用,但是如果在应用程序运行期间设置了时间,则CLOCK_REALTIME
的耗时概念也会改变。为了避免这种情况(可能不太可能),我建议使用CLOCK_MONOTONIC
或CLOCK_MONOTONIC_RAW
(如果存在的话)。从手册页中的描述中
CLOCK_REALTIME
System-wide real-time clock. Setting this clock requires appro-
priate privileges.
CLOCK_MONOTONIC
Clock that cannot be set and represents monotonic time since
some unspecified starting point.
CLOCK_MONOTONIC_RAW (since Linux 2.6.28; Linux-specific)
Similar to CLOCK_MONOTONIC, but provides access to a raw hard-
ware-based time that is not subject to NTP adjustments.
CLOCK_MONOTONIC
可能受NTP调整的影响,而CLOCK_MONOTONIC_RAW
则不受此影响。所有这些时钟的分辨率通常为1纳秒(请使用clock_getres()
进行检查),但是出于您的目的,低于1微秒的分辨率就足够了。计算耗时(以微秒为单位)
#define USED_CLOCK CLOCK_MONOTONIC // CLOCK_MONOTONIC_RAW if available
#define NANOS 1000000000LL
int main(int argc, char *argv[]) {
/* Whatever */
struct timespec begin, current;
long long start, elapsed, microseconds;
/* set up start time data */
if (clock_gettime(USED_CLOCK, &begin)) {
/* Oops, getting clock time failed */
exit(EXIT_FAILURE);
}
/* Start time in nanoseconds */
start = begin.tv_sec*NANOS + begin.tv_nsec;
/* Do something interesting */
/* get elapsed time */
if (clock_gettime(USED_CLOCK, ¤t)) {
/* getting clock time failed, what now? */
exit(EXIT_FAILURE);
}
/* Elapsed time in nanoseconds */
elapsed = current.tv_sec*NANOS + current.tv_nsec - start;
microseconds = elapsed / 1000 + (elapsed % 1000 >= 500); // round up halves
/* Display time in microseconds or something */
return EXIT_SUCCESS;
}
关于c - clock_gettime和CLOCK_PROCESS_CPUTIME_ID的数字错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11900904/