Struct Timespec Utilities

There are a number of different representations for time in C and C++, ‘struct timespec’ was added in C++11 to provide a representation of times that range beyond a simple integer. A ‘struct timespec’ contains two long fields, one for seconds and another for nanoseconds. Unlike the std::chrono classes, there are no literal operators or other supporting functions for timespec. C++17 has added std::timespec but that still lacks literals and other operators.

Examples

The utilities can be found in my github repository:

https://github.com/stephanfr/TimespecUtilities

Including the ‘TimespecUtilities.hpp’ header file is all that is required. Literal suffix operators ‘_s’ for seconds and ‘_ms’ for milliseconds are defined as well as addition, subtraction and scalar multiplication operators. Examples follow:

const struct timespec five_seconds = 5_s;
const struct timespec one_and_one_half_seconds = 1.5_s;
const struct timespec five_hundred_milliseconds = 500_ms;

const struct timespec six_and_one_half_seconds = five_seconds + one_and_one_half_seconds;
const struct timespec three_and_one_half_seconds = five_seconds - one_and_one_half_seconds;

const struct timespec ten_seconds = five_seconds * 2;
const struct timespec fifty_milliseconds = five_hundred_milliseconds * 0.1;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s