揮発性のメモ2

知識をメモ書きしておく

clock_gettimeで指定するクロックの分解能を表示する

時刻をミリ秒まで欲しいんだけど、CLOCK_REALTIME_COARSE って精度十分だっけかなぁ
というのを調べる話


clock_getres() で、どれだけ細かく時間が測定できるかがわかる

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

int main() {
    struct timespec ts;

    clock_getres(CLOCK_MONOTONIC_COARSE , &ts);
    printf("CLOCK_MONOTONIC_COARSE : %ld.%09ld seconds\n", ts.tv_sec, ts.tv_nsec);

    clock_getres(CLOCK_MONOTONIC, &ts);
    printf("CLOCK_MONOTONIC        : %ld.%09ld seconds\n", ts.tv_sec, ts.tv_nsec);

    clock_getres(CLOCK_REALTIME_COARSE , &ts);
    printf("CLOCK_REALTIME_COARSE  : %ld.%09ld seconds\n", ts.tv_sec, ts.tv_nsec);

    clock_getres(CLOCK_REALTIME, &ts);
    printf("CLOCK_REALTIME         : %ld.%09ld seconds\n", ts.tv_sec, ts.tv_nsec);

  return 0;
}

man clock_gettime (2): クロックと時間の関数



実行例1:そのへんのパソコン

$ /tmp/a.out
CLOCK_MONOTONIC_COARSE : 0.004000000 seconds
CLOCK_MONOTONIC        : 0.000000001 seconds
CLOCK_REALTIME_COARSE  : 0.004000000 seconds
CLOCK_REALTIME         : 0.000000001 seconds

実行例2:そのへんのARMボード

$ /tmp/a.out
CLOCK_MONOTONIC_COARSE : 0.010000000 seconds
CLOCK_MONOTONIC        : 0.000000001 seconds
CLOCK_REALTIME_COARSE  : 0.010000000 seconds
CLOCK_REALTIME         : 0.000000001 seconds

というわけで CLOCK_REALTIME_COARSE ではミリ秒を得られなかったので、仕方ないので CLOCK_REALTIME を使う。