getpid()调用mach_absolute_time进行时间测量

时间:2013-06-13 14:14:52

标签: iphone macos timer

文章本身就在这里:https://developer.apple.com/library/mac/#qa/qa1398/_index.html

在调用mach_absolute_time之后,调用getpid()。根据文档,此函数返回调用进程的id。我不明白为什么会在这里以及作者在时间测量的背景下所说的不准确的结果。

以下是我想知道的代码:

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;

    return elapsedNano;
}

1 个答案:

答案 0 :(得分:0)

作者提供了示例代码,说明如何进行精确的定时测量。我相信他/她只是将getpid()用作要测量的函数调用的示例(函数名称为GetPIDTimeInNanoseconds)。

关于不准确评论,我认为作者建议您采用多个读数并对结果进行平均以获得更高的准确度。例如,您可以执行以下操作,而不是启动和停止时钟:

int numberOfReadings = 5;
uint64_t elapsedTimeAccumulated = 0;
for (int i = 0; i < numberOfReadings; i++) {
    start = mach_absolute_time();
    (void) getpid();
    end = mach_absolute_time();
    elapsedTimeAccumulated += end - start;
}
// Average
elapsed = elapsedTimeAccumulated / numberOfReadings;