C++ Timing

Overview

Timing and delay functions, by their very nature, a somewhat platform specific. The C and C++ languages do make some attempt to standardize these, in where they provide a standardized front-end function that then goes and calls system-specific functions.

Time-Related Libraries

File Name Availiable For Contains Description
<chrono>      
<time.h>/<ctime>   nanosleep()
clock_t
time_t
 
<unistd.h>   sleep()
usleep()
 

Creating Delays

Note that many of these functions will not be defined for embedded systems.

unistd.h

unistd.h provides POSIX-compliant delay functions, which work in both C and C++ code. It is available natively on Linux and MacOS, but not Windows. It is available in Windows via Unix-compatibility layers such as CygWin and MinGW.

usleep() is deprecated, and not present in the latest version of the POSIX standard.

Note that when using nanosleep(), your resolution will likely be far smaller than the minimum time-step that the system supports, and your delay will be rounded

Some examples…

time.h

time.h provides POSIX-compliant delay functions, which work in both C and C++ code. It is available natively on Linux and MacOS, but not Windows. It is available in Windows via Unix-compatibility layers such as CygWin and MinGW.

usleep() is deprecated, and not present in the latest version of the POSIX standard.

Note that when using nanosleep(), your resolution will likely be far smaller than the minimum time-step that the system supports, and your delay will be rounded

Some examples…

Windows.h

This method only works if you are compiling on Windows.

Boost

The Boost library has delay functionalies.

C++11

C++11 allows the use of the standard library to create delays in the current thread. These functions seem to have been copied across from the Boost libraries.