加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

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

发布时间:2020-12-14 01:19:14 所属栏目:Linux 来源:网络整理
导读: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.
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/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 = %en",sum);
  printf("deltaT = %e sn",get_elapsed_time(&before,&after));

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读