Linux和OS X上的C语言中的ns精度单调时钟

Linux和OS X上的C语言中的ns精度单调时钟,第1张

概述clock_gettime(CLOCK_MONOTONIC,…)在 Linux中可用,但在OS X中不可用.Mach计时器在OS X中可用,但在Linux中不可用. 如何在C中获得ns精度单调时钟,这在Linux和OS X上都有效? /* This is based on the snippet current_utc_time.c from:https://gist.github.com/j clock_gettime(CLOCK_MONOTONIC,…)在 Linux中可用,但在OS X中不可用.Mach计时器在OS X中可用,但在linux中不可用.

如何在C中获得ns精度单调时钟,这在linux和OS X上都有效?

解决方法
/* This is based on the snippet current_utc_time.c from:https://gist.github.com/jbenet/1087739On 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));}
总结

以上是内存溢出为你收集整理的Linux和OS X上的C语言中的ns精度单调时钟全部内容,希望文章能够帮你解决Linux和OS X上的C语言中的ns精度单调时钟所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/1027266.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存