clock_gettime(CLOCK_MONOTONIC, ...)
在Linux上可用,但在OS X上不可用。 Mach计时器在OS X上可用,但在Linux上不可用。
我如何在C语言中获得一个同时适用于Linux和OS X的纳秒级单调时钟?
clock_gettime(CLOCK_MONOTONIC, ...)
在Linux上可用,但在OS X上不可用。 Mach计时器在OS X上可用,但在Linux上不可用。
我如何在C语言中获得一个同时适用于Linux和OS X的纳秒级单调时钟?
/*
This is based on the snippet current_utc_time.c from:
https://gist.github.com/jbenet/1087739
On OS X, compile with: gcc get_monotonic_time.c
Linux, compile with: gcc get_monotonic_time.c -lrt
*/
#include <time.h>
#include <sys/time.h>
#include <stdio.h>
#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#endif
// Use clock_gettime in linux, clock_get_time in OS X.
void get_monotonic_time(struct timespec *ts){
#ifdef __MACH__
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
ts->tv_sec = mts.tv_sec;
ts->tv_nsec = mts.tv_nsec;
#else
clock_gettime(CLOCK_MONOTONIC, ts);
#endif
}
double get_elapsed_time(struct timespec *before, struct timespec *after){
double deltat_s = after->tv_sec - before->tv_sec;
double deltat_ns = after->tv_nsec - before->tv_nsec;
return deltat_s + deltat_ns*1e-9;
}
int main(){
// Do something and time how long it takes.
struct timespec before, after;
get_monotonic_time(&before);
double sum=0.;
unsigned u;
for(u=1; u<100000000; u++)
sum += 1./u/u;
get_monotonic_time(&after);
printf("sum = %e\n", sum);
printf("deltaT = %e s\n", get_elapsed_time(&before,&after));
}
mach_absolute_time
代替对host_get_clock_service
、clock_get_time
和mach_port_deallocate
的调用。 - JWWalker我使用了Douglas的答案(被接受的答案),他的参考资料以及其他在互联网上流传的示例(例如this question)。
这个答案包括了我的版本的代码,它模拟了CLOCK_REALTIME
和CLOCK_MONOTONIC
的clock_gettime
函数。它还模拟了绝对单调时间的clock_nanosleep()
函数。该代码托管在GitHub 这里。
为了使其工作,你的代码中唯一需要的额外部分是
#ifdef __MACH__
timing_mach_init();
#endif
然后,您可以像使用实际符合 POSIX 规范(具有实时扩展)的系统一样使用 clock_gettime()
和 clock_nanosleep_abstime()
。
mach_port_deallocate(mach_host_self(), timing_mach_g.cclock)
。 - ChisholmKyle