実行時間を計る (VC# 2008)

プログラムの実行時間を計るには、QueryPerformanceCounter を使う。これには、CPU内蔵のカウンターを使っていると思われる。

  1. using System.Runtime.InteropServices; する
  2. クラスに次の宣言を加えて、QueryPerformanceCounter、QueryPerformanceFrequency を使えるようにする
    [DllImport("kernel32.dll")]
    extern static short QueryPerformanceCounter(ref long x);
    [DllImport("kernel32.dll")]
    extern static short QueryPerformanceFrequency(ref long x);
  3. long ctr;
    QueryPerformanceCounter(ref ctr);
    で値がctrに入るので、2回実行するとその差が時間
  4. 時間の精度は、
    long f;
    QueryPerformanceFrequency(ref f);
    でわかる。1/f秒がカウンターの1に該当する。