Mac OS X中的clock_gettime替代方案

Del*_*ani 65 c macos time clock

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

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.)
Run Code Online (Sandbox Code Playgroud)

它似乎clock_gettime没有在Mac OS X中实现.是否有另一种方法可以在纳秒内获得纪元时间?不幸的是在几微秒内.gettimeofday

jbe*_*net 127

经过几个小时的不同回答,博客和标题,我发现了一种可移植的方式来获取当前时间:

#include <time.h>
#include <sys/time.h>

#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#endif



struct timespec ts;

#ifdef __MACH__ // OS X does not have clock_gettime, use clock_get_time
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), CALENDAR_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_REALTIME, &ts);
#endif
Run Code Online (Sandbox Code Playgroud)

或者查看这个要点:https://gist.github.com/1087739

希望这能节省一些时间.干杯!

  • 有没有人可能计时上面的`__MACH__`代码?使用独立的微秒计时器(经过充分测试)我得到的印象是,上述代码的两次调用成本约为25微秒. (4认同)
  • host_get_clock_service贵吗?是否需要为进程缓存它?它可以重复使用吗?线程安全?谢谢 - :) (3认同)
  • @NikolayVyahhi是的!我把它们放在要点中.虽然你没有找到它们,但也许最好将它们添加到答案中. (3认同)

Ser*_*y D 34

以上解决方案都没有回答这个问题.他们要么没有给你绝对的Unix时间,要么他们的准确度是1微秒.jbenet最流行的解决方案是缓慢的(~6000ns)并且不计入纳秒,即使它的返回表明如此.下面是对jbenet和Dmitri B建议的2个解决方案的测试,以及我对此的看法.您可以在不更改的情况下运行代码.

第三种解决方案确实以纳秒计数,并为您提供相当快的绝对Unix时间(~90ns).所以如果有人发现它有用 - 请在这里告诉我们:-).我将坚持使用Dmitri B(代码中的解决方案#1) - 它更符合我的需求.

我需要商业质量替代clock_gettime()来进行pthread_ ... timed ..调用,并发现这个讨论非常有用.多谢你们.

/*
 Ratings of alternatives to clock_gettime() to use with pthread timed waits:
    Solution 1 "gettimeofday":
        Complexity      : simple
        Portability     : POSIX 1
        timespec        : easy to convert from timeval to timespec
        granularity     : 1000 ns,
        call            : 120 ns,
        Rating          : the best.

    Solution 2 "host_get_clock_service, clock_get_time":
        Complexity      : simple (error handling?)
        Portability     : Mac specific (is it always available?)
        timespec        : yes (struct timespec return)
        granularity     : 1000 ns (don't be fooled by timespec format)
        call time       : 6000 ns
        Rating          : the worst.

    Solution 3 "mach_absolute_time + gettimeofday once":
        Complexity      : simple..average (requires initialisation)
        Portability     : Mac specific. Always available
        timespec        : system clock can be converted to timespec without float-math
        granularity     : 1 ns.
        call time       : 90 ns unoptimised.
        Rating          : not bad, but do we really need nanoseconds timeout?

 References:
 - OS X is UNIX System 3 [U03] certified
    http://www.opengroup.org/homepage-items/c987.html

 - UNIX System 3 <--> POSIX 1 <--> IEEE Std 1003.1-1988
    http://en.wikipedia.org/wiki/POSIX
    http://www.unix.org/version3/

 - gettimeofday() is mandatory on U03,
   clock_..() functions are optional on U03,
   clock_..() are part of POSIX Realtime extensions
    http://www.unix.org/version3/inttables.pdf

 - clock_gettime() is not available on MacMini OS X
    (Xcode > Preferences > Downloads > Command Line Tools = Installed)

 - OS X recommends to use gettimeofday to calculate values for timespec
    https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/pthread_cond_timedwait.3.html

 - timeval holds microseconds, timespec - nanoseconds
    http://www.gnu.org/software/libc/manual/html_node/Elapsed-Time.html

 - microtime() is used by kernel to implement gettimeofday()
    http://ftp.tw.freebsd.org/pub/branches/7.0-stable/src/sys/kern/kern_time.c

 - mach_absolute_time() is really fast
    http://www.opensource.apple.com/source/Libc/Libc-320.1.3/i386/mach/mach_absolute_time.c

 - Only 9 deciaml digits have meaning when int nanoseconds converted to double seconds
    Tutorial: Performance and Time post uses .12 precision for nanoseconds
    http://www.macresearch.org/tutorial_performance_and_time

 Example:
    Three ways to prepare absolute time 1500 milliseconds in the future to use with pthread timed functions.

 Output, N = 3, stock MacMini, OSX 10.7.5, 2.3GHz i5, 2GB 1333MHz DDR3:
    inittime.tv_sec = 1390659993
    inittime.tv_nsec = 361539000
    initclock = 76672695144136
    get_abs_future_time_0() : 1390659994.861599000
    get_abs_future_time_0() : 1390659994.861599000
    get_abs_future_time_0() : 1390659994.861599000
    get_abs_future_time_1() : 1390659994.861618000
    get_abs_future_time_1() : 1390659994.861634000
    get_abs_future_time_1() : 1390659994.861642000
    get_abs_future_time_2() : 1390659994.861643671
    get_abs_future_time_2() : 1390659994.861643877
    get_abs_future_time_2() : 1390659994.861643972
 */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>       /* gettimeofday */
#include <mach/mach_time.h> /* mach_absolute_time */
#include <mach/mach.h>      /* host_get_clock_service, mach_... */
#include <mach/clock.h>     /* clock_get_time */

#define BILLION 1000000000L
#define MILLION 1000000L

#define NORMALISE_TIMESPEC( ts, uint_milli )            \
    do {                                                \
        ts.tv_sec += uint_milli / 1000u;                \
        ts.tv_nsec += (uint_milli % 1000u) * MILLION;   \
        ts.tv_sec += ts.tv_nsec / BILLION;              \
        ts.tv_nsec = ts.tv_nsec % BILLION;              \
    } while (0)

static mach_timebase_info_data_t timebase = { 0, 0 }; /* numer = 0, denom = 0 */
static struct timespec           inittime = { 0, 0 }; /* nanoseconds since 1-Jan-1970 to init() */
static uint64_t                  initclock;           /* ticks since boot to init() */

void init()
{
    struct timeval  micro;      /* microseconds since 1 Jan 1970 */

    if (mach_timebase_info(&timebase) != 0)
        abort();                            /* very unlikely error */

    if (gettimeofday(&micro, NULL) != 0)
        abort();                            /* very unlikely error */

    initclock = mach_absolute_time();

    inittime.tv_sec = micro.tv_sec;
    inittime.tv_nsec = micro.tv_usec * 1000;
    printf("\tinittime.tv_sec = %ld\n", inittime.tv_sec);
    printf("\tinittime.tv_nsec = %ld\n", inittime.tv_nsec);
    printf("\tinitclock = %ld\n", (long)initclock);
}

/*
 * Get absolute future time for pthread timed calls
 *  Solution 1: microseconds granularity
 */
struct timespec get_abs_future_time_coarse(unsigned milli)
{
    struct timespec future;         /* ns since 1 Jan 1970 to 1500 ms in the future */
    struct timeval  micro = {0, 0}; /* 1 Jan 1970 */

    (void) gettimeofday(&micro, NULL);
    future.tv_sec = micro.tv_sec;
    future.tv_nsec = micro.tv_usec * 1000;
    NORMALISE_TIMESPEC( future, milli );
    return future;
}

/*
 * Solution 2: via clock service
 */
struct timespec get_abs_future_time_served(unsigned milli)
{
    struct timespec     future;
    clock_serv_t        cclock;
    mach_timespec_t     mts;

    host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
    clock_get_time(cclock, &mts);
    mach_port_deallocate(mach_task_self(), cclock);
    future.tv_sec = mts.tv_sec;
    future.tv_nsec = mts.tv_nsec;
    NORMALISE_TIMESPEC( future, milli );
    return future;
}

/*
 * Solution 3: nanosecond granularity
 */
struct timespec get_abs_future_time_fine(unsigned milli)
{
    struct timespec future;     /* ns since 1 Jan 1970 to 1500 ms in future */
    uint64_t        clock;      /* ticks since init */
    uint64_t        nano;       /* nanoseconds since init */

    clock = mach_absolute_time() - initclock;
    nano = clock * (uint64_t)timebase.numer / (uint64_t)timebase.denom;
    future = inittime;
    future.tv_sec += nano / BILLION;
    future.tv_nsec += nano % BILLION;
    NORMALISE_TIMESPEC( future, milli );
    return future;
}

#define N 3

int main()
{
    int                 i, j;
    struct timespec     time[3][N];
    struct timespec   (*get_abs_future_time[])(unsigned milli) =
    {
        &get_abs_future_time_coarse,
        &get_abs_future_time_served,
        &get_abs_future_time_fine
    };

    init();
    for (j = 0; j < 3; j++)
        for (i = 0; i < N; i++)
            time[j][i] = get_abs_future_time[j](1500);  /* now() + 1500 ms */

    for (j = 0; j < 3; j++)
        for (i = 0; i < N; i++)
            printf("get_abs_future_time_%d() : %10ld.%09ld\n",
                   j, time[j][i].tv_sec, time[j][i].tv_nsec);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Jen*_*edt 32

实际上,在Sierra 10.12之前似乎没有为macOS实现.您可能希望查看此博客条目,但这似乎不再可用.主要思想在以下代码片段中:

#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;
}
Run Code Online (Sandbox Code Playgroud)

  • 永远不要混淆单调和实时.当NTP守护程序更正系统时钟时,实时可能会跳转.真的,它们是两个完全不同的东西. (9认同)
  • 我不想要单调的时间,我想要自纪元以来的实时,以纳秒为单位. (4认同)
  • @Delan,我不明白你为什么会这么想,这对于计算数年数量级的东西来说是无用的预测.通常你需要纳秒来计算一个函数左右.然后在博客中完成之前和之后花费时间就足够了.但是你总是可以通过在程序开头使用`gettimeofday`和`mach_absolute_time`然后添加东西来模拟它. (3认同)
  • 请改用此链接:http://web.archive.org/web/20100517095152/http://www.wand.net.nz/~smr26/wordpress/2009/01/19/monotonic-time-in-mac- OS-X /评论页-1 / (3认同)
  • "博客条目"现已破裂:( (2认同)
  • 顺便说一下,代码封装了一个变量的乘法和除法,后来乘以它会不必要地降低净计算的精度.对于整数数学,最好在任何除法之前先进行*所有乘法*. (2认同)

小智 30

#if defined(__MACH__) && !defined(CLOCK_REALTIME)
#include <sys/time.h>
#define CLOCK_REALTIME 0
// clock_gettime is not implemented on older versions of OS X (< 10.12).
// If implemented, CLOCK_REALTIME will have already been defined.
int clock_gettime(int /*clk_id*/, struct timespec* t) {
    struct timeval now;
    int rv = gettimeofday(&now, NULL);
    if (rv) return rv;
    t->tv_sec  = now.tv_sec;
    t->tv_nsec = now.tv_usec * 1000;
    return 0;
}
#endif
Run Code Online (Sandbox Code Playgroud)

  • 如果你使用CLOCK_REALTIME或CLOCK_MONOTONIC,你还应该定义:#define CLOCK_REALTIME 0 #define CLOCK_MONOTONIC 0 (8认同)
  • 因为a)精度低了1000倍(虽然不是那么糟糕,因为`clock_gettime`真正返回的时间粒度很少(从不)是1纳秒),而b)`gettimeofday`返回的时间是不同的,非单调.它可能会疯狂地跳跃(例如,当夏令时发生时),或者甚至可能以稍慢/更快(!)的速度运行,在时间服务器同步发生之后,时间服务可能希望避免时间的小突然变化. (5认同)
  • 不幸的是,一天中的时间不是单调的时钟.(单调时钟专门用于避免与时钟相关的所有问题,包括管理员或NTP更改时间,闰秒,时区等) (4认同)

Cha*_*acy 21

技术问答QA1398:技术问答QA1398:马赫绝对时间单位,基本上是你想要的功能,描述了你需要的一切mach_absolute_time.

这是来自该页面的示例代码的稍早版本,它使用Mach调用执行所有操作(当前版本使用AbsoluteToNanosecondsCoreServices).在当前的OS X中(即,在x86_64上的Snow Leopard上),绝对时间值实际上是以纳秒为单位,因此实际上根本不需要任何转换.所以,如果你很好并且编写可移植代码,你就会转换,但如果你只是为自己做一些快速而又脏的事情,你就不用费心了.

FWIW,mach_absolute_time真的快.

uint64_t GetPIDTimeInNanoseconds(void)
{
    uint64_t        start;
    uint64_t        end;
    uint64_t        elapsed;
    uint64_t        elapsedNano;
    static mach_timebase_info_data_t    sTimebaseInfo;

    // Start the clock.

    start = mach_absolute_time();

    // Call getpid. This will produce inaccurate results because 
    // we're only making a single system call. For more accurate 
    // results you should call getpid multiple times and average 
    // the results.

    (void) getpid();

    // Stop the clock.

    end = mach_absolute_time();

    // Calculate the duration.

    elapsed = end - start;

    // Convert to nanoseconds.

    // If this is the first time we've run, get the timebase.
    // We can use denom == 0 to indicate that sTimebaseInfo is 
    // uninitialised because it makes no sense to have a zero 
    // denominator is a fraction.

    if ( sTimebaseInfo.denom == 0 ) {
        (void) mach_timebase_info(&sTimebaseInfo);
    }

    // Do the maths. We hope that the multiplication doesn't 
    // overflow; the price you pay for working in fixed point.

    elapsedNano = elapsed * sTimebaseInfo.numer / sTimebaseInfo.denom;

    printf("multiplier %u / %u\n", sTimebaseInfo.numer, sTimebaseInfo.denom);
    return elapsedNano;
}
Run Code Online (Sandbox Code Playgroud)


Jam*_*ald 14

请注意,macOS Sierra 10.12现在支持clock_gettime():

#include <stdio.h>
#include <time.h>

int main() {
    struct timespec res;
    struct timespec time;

    clock_getres(CLOCK_REALTIME, &res);
    clock_gettime(CLOCK_REALTIME, &time);

    printf("CLOCK_REALTIME: res.tv_sec=%lu res.tv_nsec=%lu\n", res.tv_sec, res.tv_nsec);
    printf("CLOCK_REALTIME: time.tv_sec=%lu time.tv_nsec=%lu\n", time.tv_sec, time.tv_nsec);
}
Run Code Online (Sandbox Code Playgroud)

它确实提供纳秒; 但是,分辨率是1000,因此它(有效)限制为微秒:

CLOCK_REALTIME: res.tv_sec=0 res.tv_nsec=1000
CLOCK_REALTIME: time.tv_sec=1475279260 time.tv_nsec=525627000
Run Code Online (Sandbox Code Playgroud)

您需要XCode 8或更高版本才能使用此功能.编译为使用此功能的代码将无法在Mac OS X(10.11或更早版本)的版本上运行.

  • 需要注意的是:如果使用XCode 8(或更高版本)构建,但是目标版本的OSX早于10.12,您将在编译时找到`clock_gettime`符号,但在10.11或更低版本上运行二进制文件时,您将获得"dyld:未找到符号:_clock_gettime"因为编译器生成了弱符号. (2认同)

ilc*_*avo 9

谢谢你的帖子

我想你可以添加以下几行

#ifdef __MACH__
#include <mach/mach_time.h>
#define CLOCK_REALTIME 0
#define CLOCK_MONOTONIC 0
int clock_gettime(int clk_id, struct timespec *t){
    mach_timebase_info_data_t timebase;
    mach_timebase_info(&timebase);
    uint64_t time;
    time = mach_absolute_time();
    double nseconds = ((double)time * (double)timebase.numer)/((double)timebase.denom);
    double seconds = ((double)time * (double)timebase.numer)/((double)timebase.denom * 1e9);
    t->tv_sec = seconds;
    t->tv_nsec = nseconds;
    return 0;
}
#else
#include <time.h>
#endif
Run Code Online (Sandbox Code Playgroud)

让我知道您获得的延迟和粒度

  • 如果你缓存了`mach_timebase_info`调用(可能带有静态变量以保持整洁)会更好.`mach_timebase_info()`是一个系统调用,在我的机器上需要大约180ns.与`mach_absolute_time()`的〜22ns相反,它基本上只是采样`rdtsc`. (3认同)