Skip to content

Instantly share code, notes, and snippets.

@ykst
Created January 28, 2015 14:11
Show Gist options
  • Save ykst/bd167415f397478f7181 to your computer and use it in GitHub Desktop.
Save ykst/bd167415f397478f7181 to your computer and use it in GitHub Desktop.
実行時間を計測する簡易マクロ

実行時間を計測する簡易マクロ

コードブロックの実行時間をなるべく非侵入的に計測したい場合に、for制御構文を流用するやり方です。 for文の初期化節で開始時刻を記録し、一回だけループを回して終了条件節でダンプを行います。 C++のスタックにオブジェクトを作ってデストラクタを走らせるパターンがよくありますが、Cでも同じような事は出来ます。 色々応用出来ると思います。

static inline bool ____benchmark_check_time(char const * const comment, uint64_t const start, uint64_t const tick)
{
    if (!tick) return true;
    uint64_t const elapsed = mach_absolute_time() - start;
    mach_timebase_info_data_t base;
    mach_timebase_info(&base);

    uint64_t const nsec = elapsed * base.numer / base.denom;
    printf("%s: %.3fms\n", comment, nsec / 1000000.0);
    return false;
}

#ifdef ENABLE_BENCHMARK
#  define BENCHMARK(comment) for(uint64_t ____tick = 0, ____start = mach_absolute_time(); ____benchmark_check_time(comment, ____start, ____tick); ++____tick)
#else
#  define BENCHMARK(comment)
#endif

##例

void test()
{
    BENCHMARK(“block”) {
        do_something();
    }

    BENCHMARK(“instruction”)
    [something callBlock:^{
        do_something();
    }];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment