C で、処理にかかった時間を計る方法

以下の関数を用意して、
#include <sys/time.h>

int cputime()
{
    struct timeval tp;
    void *tzp;

    tzp = NULL;
    gettimeofday(&tp,tzp);

    return tp.tv_sec*1000 + tp.tv_usec/1000;
}
void foo {
    int starttime, endtime
    startime = cputime();

    // 処理

    endtime = cputime();

printf("CPU Time: %d ms\n", endtime - starttime);
}
とすればよい。これで、ミリ秒(ms)の値が得られる。ポイントは gettimeofday という関数を使うこと。 追記: 最近のCPU はあまりにも処理が速すぎて、上の関数では常にゼロミリ秒しか返さない場合がある。もともと gettimeofday はマイクロ秒単位で結果が返ってきている。従ってもっと細かい精度が必要なときに以下のようにする。
#include <sys/time.h>
double cputime()
{
  struct timeval tp;
  void *tzp;

  tzp = NULL;

  gettimeofday(&tp,tzp);

  return tp.tv_sec + (double)tp.tv_usec*1e-6;
}
void foo {
    double starttime, endtime
    startime = cputime();

    // 処理

    endtime = cputime();

printf("CPU Time: %10.6f ms\n", endtime - starttime);
}
Updated: 2006/11/16 Original: 2006/11/06
トラックバック URL: https://perltips.twinkle.cc/trackback/137