ANSI Cを使用してミリ秒単位で時間を測定するには?

1 秒より優れた時間分解能を提供する ANSI C 関数はありませんが、POSIX 関数 gettimeofday マイクロ秒の分解能を提供します。時計機能は、プロセスの実行に費やされた時間を測定するだけであり、多くのシステムでは正確ではありません.

この関数は次のように使用できます:

struct timeval tval_before, tval_after, tval_result;

gettimeofday(&tval_before, NULL);

// Some code you want to time, for example:
sleep(1);

gettimeofday(&tval_after, NULL);

timersub(&tval_after, &tval_before, &tval_result);

printf("Time elapsed: %ld.%06ld\n", (long int)tval_result.tv_sec, (long int)tval_result.tv_usec);

これは Time elapsed: 1.000870 を返します


#include <time.h>
clock_t uptime = clock() / (CLOCKS_PER_SEC / 1000);

私は常に clock_gettime() 関数を使用して、CLOCK_MONOTONIC クロックから時間を返します。返される時間は、エポックのシステム起動など、過去の特定されていない時点からの時間 (秒およびナノ秒) です。

#include <stdio.h>
#include <stdint.h>
#include <time.h>

int64_t timespecDiff(struct timespec *timeA_p, struct timespec *timeB_p)
{
  return ((timeA_p->tv_sec * 1000000000) + timeA_p->tv_nsec) -
           ((timeB_p->tv_sec * 1000000000) + timeB_p->tv_nsec);
}

int main(int argc, char **argv)
{
  struct timespec start, end;
  clock_gettime(CLOCK_MONOTONIC, &start);

  // Some code I am interested in measuring 

  clock_gettime(CLOCK_MONOTONIC, &end);

  uint64_t timeElapsed = timespecDiff(&end, &start);
}