Timing in C++

Overview

How to do timing gracefully in C++?

Function OS Header Multi-thread Accuracy
clock() clock_t Windows/Linux <time.h> Not Support millisecond
time() time_t Windows/Linux <time.h> Support (defraud) second
gettimeofday()/
struct timeval
UNIX/Linux <time.h>
<sys/time.h>
Support microsecond
clock_gettime()/
struct timespec
UNIX/Linux <time.h>
<sys/time.h>
Support nanosecond

clock() clock_t

clock() will return a type of clock_t, which is a long, stands for program execution time. The unit is the number of CPU clock timing units (clock ticks).

1
2
3
4
5
6
7
8
clock_t time_start;
clock_t time_end;
time_start= clock();
// func()
time_end= clock();
// diff-second
double time_diff_sec = ((double)(time_end- time_start) / CLOCKS_PER_SEC);
printf("lib: time diff: %fs.\n", time_diff_sec);

time() time_t

time() will return the time elapsed from UTC 1970-1-1 00:00:00 to now in seconds.

1
2
3
4
5
6
7
8
9
10
11
time_t time_start;
time_t time_end;
time_start = time(NULL);
// func()
time_end = time(NULL);
// diff-second
double time_diff_sec = difftime(time_end, time_start);
// print
printf("lib: start time: %s", ctime(&time_start));
printf("lib: end time: %s", ctime(&time_end));
printf("lib: time diff: %fs.\n", time_diff_sec);

gettimeofday()/ struct timeval

The timeval returned by the function gettimeofday() is Epoch(00:00:00 1970-01-01 UTC) to the time when the struct timeval is created, tv_sec is the second part, and tv_usec is the microsecond part. timeval is defined as the following in time.h.

1
2
3
4
struct timeval { 
 time_t tv_sec;     /* Seconds. */
 suseconds_t tv_usec;  /* Microseconds. */
};
1
2
3
4
5
6
struct timeval t1, t2;
gettimeofday(&t1, NULL);
// func()
gettimeofday(&t2, NULL);
// diff-second
double time_diff_sec = (t2.tv_sec-t1.tv_sec) + (t2.tv_usec-t1.tv_usec)/1000000;

clock_gettime()/ struct timespec

The timespec returned by the function clock_gettime() is the time from the specific time to the creation of the struct timeval, tv_sec is the second part, and tv_usec is the microsecond part. timespec is defined as the following in time.h.

1
2
3
4
struct timespec {
  time_t tv_sec; /* Seconds. */
  long tv_nsec; /* Nanoseconds. */
};

Useful specific time:

CLOCK_REALTIME System time from UTC 1970-1-1 00:00:00

CLOCK_MONOTONIC System start up time

CLOCK_PROCESS_CPUTIME_ID This process execution time

CLOCK_THREAD_CPUTIME_ID This thread execution time

1
2
3
4
5
6
struct timespec t1, t2;
clock_gettime(CLOCK_MONOTONIC, &t1);
// func()
clock_gettime(CLOCK_MONOTONIC, &t2);
// diff-second
double time_diff_sec = (t2.tv_sec-t1.tv_sec) + (t2.tv_usec-t1.tv_usec)/1000000;

Reference: cplusplus