How do I measure a time interval in C?

2019-01-05 09:19发布

I would like to measure time in C, and I am having a tough time figuring it out, all I want is something like this:

  • start a timer
  • run a method
  • stop the timer
  • report the time taken (at least to micro accuracy)

Any help would be appreciated.

(I am compiling in windows using mingw)

标签: c timer
8条回答
别忘想泡老子
2楼-- · 2019-01-05 09:46

Using the time.h library, try something like this:

long start_time, end_time, elapsed;

start_time = clock();
// Do something
end_time = clock();

elapsed = (end_time - start_time) / CLOCKS_PER_SEC * 1000;
查看更多
欢心
3楼-- · 2019-01-05 09:58

If your Linux system supports it, clock_gettime(CLOCK_MONOTONIC) should be a high resolution timer that is unaffected by system date changes (e.g. NTP daemons).

查看更多
登录 后发表回答