スキップしてメイン コンテンツに移動

C言語で実行時間測定

C言語で実行時間を測定する方法。覚書。正確さから言えばgettimeofdayかな。手軽さからならclockあたりで。Unixであれば、timeコマンドがソースの変更もなく手間もかからず簡単。Windowsの場合は、timeitコマンドリソースキットに含まれている。

% time 実行ファイル

以下、Cのコード。

clock

#include <stdio.h> #include <time.h> int main() { clock_t t1, t2; t1 = clock(); /* 処理. */ t2 = clock(); printf("%f\n", (double)(t2 - t1) / CLOCKS_PER_SEC); return 0; }

gettimeofday

#include <stdio.h> #include <time.h> #include <sys/time.h> double gettimeofday_sec() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec + tv.tv_usec * 1e-6; } int main() { double t1, t2; t1 = gettimeofday_sec(); /* 処理. */ t2 = gettimeofday_sec(); printf("%f\n", t2 - t1); return 0; }

getrusage

#include <stdio.h> #include <time.h> #include <sys/time.h> #include <sys/resource.h> double getrusage_sec() { struct rusage t; struct timeval tv; getrusage(RUSAGE_SELF, &t); tv = t.ru_utime; return tv.tv_sec + tv.tv_usec * 1e-6; } int main() { double t1, t2; t1 = getrusage_sec(); /* 処理. */ t2 = getrusage_sec(); printf("%f\n", t2 - t1); return 0; }

times

#include <stdio.h> #include <time.h> #include <unistd.h> #include <sys/time.h> #include <sys/times.h> clock_t times_clock() { struct tms t; return times(&t); } int main() { clock_t t1, t2; t1 = times_clock(); /* 処理. */ t2 = times_clock(); printf("%f\n", (double)(t2 - t1) / sysconf(_SC_CLK_TCK)); return 0; }

コメント