0

文章本身在这里: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;
}
4

1 回答 1

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;
于 2013-11-06T12:29:54.713 回答