mac os x绝对时间与时钟时间之间转换

// timebase_demo.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <mach/mach.h>
#include <mach/mach_time.h>

#define DEFAULT_SLEEP_TIME 1
#define MAXIMUM_SLEEP_TIME 60

int
main(int argc, char **argv)
{
    kern_return_t kr;
    u_int64_t     t1, t2, diff;
    double        abs2clock;
    int           sleeptime = DEFAULT_SLEEP_TIME;

    mach_timebase_info_data_t info;

    kr = mach_timebase_info(&info);
    if (kr != KERN_SUCCESS) {
        mach_error("mach_timebase_info:", kr);
        exit(kr);
    }

    if (argc == 2) {
        sleeptime = atoi(argv[1]);
        if ((sleeptime < 0) || (sleeptime > MAXIMUM_SLEEP_TIME))
            sleeptime = DEFAULT_SLEEP_TIME;
    } 

    t1 = mach_absolute_time();
    sleep(sleeptime);
    t2 = mach_absolute_time();
    diff = t2 - t1;

    printf("slept for %d seconds of clock time\n", sleeptime);
    printf("TB increments = %llu increments\n", diff);
    printf("absolute-to-clock conversion factor = (%u/%u) ns/increment\n",
           info.numer, info.denom);
    printf("sleeping time according to TB\n");

    abs2clock = (double)info.numer/(double)info.denom;
    abs2clock *= (double)diff;

    printf("\t= %llu increments x (%u/%u) ns/increment\n\t= %f ns\n\t= %f s\n",
           diff, info.numer, info.denom,
           abs2clock, abs2clock/(double)1000000000);

    exit(0);
}

mac os x绝对时间与时钟时间之间转换

haidragondeMacBook-Pro:7-41 haidragon$ gcc -Wall -o timebase_demo timebase_demo.c 
haidragondeMacBook-Pro:7-41 haidragon$ ls
timebase_demo   timebase_demo.c
haidragondeMacBook-Pro:7-41 haidragon$ ./timebase_demo
slept for 1 seconds of clock time
TB increments = 1002722462 increments
absolute-to-clock conversion factor = (1/1) ns/increment
sleeping time according to TB
    = 1002722462 increments x (1/1) ns/increment
    = 1002722462.000000 ns
    = 1.002722 s
haidragondeMacBook-Pro:7-41 haidragon$ ./timebase_demo 5
slept for 5 seconds of clock time
TB increments = 5003092227 increments
absolute-to-clock conversion factor = (1/1) ns/increment
sleeping time according to TB
    = 5003092227 increments x (1/1) ns/increment
    = 5003092227.000000 ns
    = 5.003092 s
haidragondeMacBook-Pro:7-41 haidragon$ 
上一篇:【NOI2019模拟2019.6.29】组合数(Lucas定理、数位dp)


下一篇:Twenty Four, Again