Clocks And 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.

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.

 

Durations

The std::chrono::duration class can be used to represent a duration of time. It also has the benefit of being able to represent a duration in many different units (e.g. seconds, milliseconds, microseconds).

Run the above example online at https://wandbox.org/permlink/KSpr5KgvSIDimNb5.

Note: To use std::chrono::duration without having to specify the units requires C++17, as template argument deduction feature is required. If you are using C++11 or C++14, you would have to change the above to:

Run the above example online at https://wandbox.org/permlink/bprXREr562iFH6dM.

To print a std::chrono::duration, you must first convert it to a specific unit-specifying overload, and then call the count() method to return the integer number of counts in this unit. This can then be easily converted into a string, or spat directly to std::cout.

Run the above example online at https://wandbox.org/permlink/9u6as1nfcpWv1cBe.

Clocks

std::chrono::high_resolution_clock

The object returned from clock::now() is a time_point.

Printing out the value of a time_point:

 

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.

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.

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

The Windows API provides the Sleep() function. This method only works if you are compiling on Windows.

Boost

The Boost library has delay functionalies.

 

Posted: May 7th, 2014 at 4:17 pm
Last Updated on: October 17th, 2017 at 6:34 am