Mac OS X 中的clock_gettime 替代方案 [英] clock_gettime alternative in Mac OS X

查看:52
本文介绍了Mac OS X 中的clock_gettime 替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在通过 MacPorts 安装必要的库后编译我在 Mac OS X 上编写的程序时,出现此错误:

When compiling a program I wrote on Mac OS X after installing the necessary libraries through MacPorts, I get this error:

In function 'nanotime':
error: 'CLOCK_REALTIME' undeclared (first use in this function)
error: (Each undeclared identifier is reported only once
error: for each function it appears in.)

clock_gettime 似乎没有在 Mac OS X 中实现.是否有其他方法可以在 纳秒 中获取纪元时间?不幸的是,gettimeofday 的单位是 微秒.

It appears that clock_gettime is not implemented in Mac OS X. Is there an alternative means of getting the epoch time in nanoseconds? Unfortunately gettimeofday is in microseconds.

推荐答案

实际上,它似乎没有在 Sierra 10.12 之前的 macOS 上实现.你可能想看看这个 博客条目.主要思想在以下代码片段中:

In effect, it seems not to be implemented for macOS before Sierra 10.12. You may want to look at this blog entry. The main idea is in the following code snippet:

#include <mach/mach_time.h>
#define ORWL_NANO (+1.0E-9)
#define ORWL_GIGA UINT64_C(1000000000)

static double orwl_timebase = 0.0;
static uint64_t orwl_timestart = 0;

struct timespec orwl_gettime(void) {
  // be more careful in a multithreaded environement
  if (!orwl_timestart) {
    mach_timebase_info_data_t tb = { 0 };
    mach_timebase_info(&tb);
    orwl_timebase = tb.numer;
    orwl_timebase /= tb.denom;
    orwl_timestart = mach_absolute_time();
  }
  struct timespec t;
  double diff = (mach_absolute_time() - orwl_timestart) * orwl_timebase;
  t.tv_sec = diff * ORWL_NANO;
  t.tv_nsec = diff - (t.tv_sec * ORWL_GIGA);
  return t;
}

这篇关于Mac OS X 中的clock_gettime 替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆