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

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

本文介绍了Linux和OS X上C语言中的ns精度单调时钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

clock_gettime(CLOCK_MONOTONIC, ...)在Linux中可用,但在OS X中不可用.Mach计时器在OS X中可用,但在Linux中不可用.

clock_gettime(CLOCK_MONOTONIC, ...) is available in Linux but not OS X. The Mach timers are available in OS X but not in Linux.

如何在C语言中获得同时在Linux和OS X上运行的ns精度单调时钟?

How can I get a ns-precision monotonic clock in C that works both on Linux and 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));

}

这篇关于Linux和OS X上C语言中的ns精度单调时钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 14:52