Time Duration

Contents[Show]

Time duration is the difference between two time points. It will be measured in time ticks.

Time duration

Time duration is a class template. std::chrono::duration consists of the type of the tick Rep and the length of a tick Period.

template<
    class Rep,
    class Period = std::ratio<1>
> class duration;

 

The tick length is by default std::ratio<1> std::ratio<1> stands for a second and can also be written as std::ratio<1,1>. Therefore, it's quite easy. std::ratio<60> is a minute and std::ratio<1,1000> a millisecond. When Rep is a floating point number, you can use it to hold fractions of time ticks.

C++11 predefines the most important time durations:

typedef duration<signed int, nano> nanoseconds;
typedef duration<signed int, micro> microseconds;
typedef duration<signed int, milli> milliseconds;
typedef duration<signed int> seconds;
typedef duration<signed int, ratio< 60>> minutes;
typedef duration<signed int, ratio<3600>> hours;

 

How much time has passed since the UNIX epoch (1.1.1970)? Thanks to type aliases for the different time durations, I can answer the question quite easily. For simplicity reasons, I ignore leap years and assume that a year has 365 days.

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// timeSinceEpoch.cpp

#include <chrono>
#include <iostream>

int main(){

  std::cout << std::fixed << std::endl;
  
  std::cout << "Time since 1.1.1970:\n" << std::endl;

  auto timeNow= std::chrono::system_clock::now();
  auto duration= timeNow.time_since_epoch();
  std::cout << duration.count() << " nanoseconds " << std::endl;

  typedef std::chrono::duration<long double,std::ratio<1,1000000>> MyMicroSecondTick;
  MyMicroSecondTick micro(duration);
  std::cout << micro.count() << " microseconds" << std::endl;
  
  typedef std::chrono::duration<long double,std::ratio<1,1000>> MyMilliSecondTick;
  MyMilliSecondTick milli(duration);
  std::cout << milli.count() << " milliseconds" << std::endl;
  
  typedef std::chrono::duration<long double> MySecondTick;
  MySecondTick sec(duration);
  std::cout << sec.count() << " seconds " << std::endl;
  
  typedef std::chrono::duration<double, std::ratio<60>> MyMinuteTick;
  MyMinuteTick myMinute(duration);
  std::cout << myMinute.count() << " minutes" << std::endl;

  typedef std::chrono::duration<double, std::ratio<60*60>> MyHourTick;
  MyHourTick myHour(duration);
  std::cout << myHour.count() << " hours" << std::endl;
  
  typedef std::chrono::duration<double, std::ratio<60*60*24*365>> MyYearTick;
  MyYearTick myYear(duration);
  std::cout << myYear.count() << " years" << std::endl;

  typedef std::chrono::duration<double, std::ratio<60*45>> MyLessonTick;
  MyLessonTick myLesson(duration);
  std::cout << myLesson.count() << " lessons" << std::endl;

  std::cout << std::endl;

}

 

In addition to the typical time duration's microsecond (line 16), millisecond (line 20), second (line 24), minute (line 28), hour (line 32), and year (line 36), I define the German school hour (45 min) in line 45.

 timeSinceEpoch

It's quite convenient to calculate with time durations.

 

Rainer D 6 P2 540x540Modernes C++ Mentoring

Be part of my mentoring programs:

 

 

 

 

Do you want to stay informed about my mentoring programs: Subscribe via E-Mail.

Calculations with time durations

The time durations support basic mathematics. In the case of multiplication or division, you can multiply or divide a time duration by a number. Of course, you can compare time durations. I explicitly want to emphasize that all these calculations and comparisons respect the units of the time durations.

It gets even better with C++14 because C++14 has a bunch of predefined time literals.

timeLiteralsEng

How much time does my 16 year old son need for his typical school day? I will answer the question in the example and show the result in different time durations.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// schoolDay.cpp

#include <iostream>
#include <chrono>

using namespace std::literals::chrono_literals;

int main(){

  std::cout << std::endl;

  constexpr auto schoolHour= 45min;

  constexpr auto shortBreak= 300s;
  constexpr auto longBreak= 0.25h;

  constexpr auto schoolWay= 15min;
  constexpr auto homework= 2h;

  constexpr auto schoolDayInSeconds= 2*schoolWay + 6 * schoolHour + 4 * shortBreak + longBreak + homework;

  std::cout << "School day in seconds: " << schoolDayInSeconds.count() << std::endl;

  std::chrono::duration<double,std::ratio<3600>> schoolDayInHours = schoolDayInSeconds;
  std::chrono::duration<double,std::ratio<60>> schoolDayInMinutes = schoolDayInSeconds;
  std::chrono::duration<double,std::ratio<1,1000>> schoolDayInMilliseconds= schoolDayInSeconds;

  std::cout << "School day in hours: " << schoolDayInHours.count() << std::endl;
  std::cout << "School day in minutes: " << schoolDayInMinutes.count() << std::endl;
  std::cout << "School day in milliseconds: " << schoolDayInMilliseconds.count() << std::endl;

  std::cout << std::endl;

}

 

The time literals are constant expressions; therefore, they can be evaluated at compile time. I have time durations for a German school hour (line 12), for a short break (line 14), for a long break (line 15), for his way to the school (line 17), and his homework (line 18). The result of the calculation schoolDaysInSeconds (line 20) is available at compile time.

schoolDay

Impressed? I'm not. His daily duty is only about 7 1/2 hours.

What's next?

The used clock gives the accuracy of the time tick. In C++, we have the clocks std::chrono::system_clock, std::chrono::steady_clock, and std::chrono::high_resolution_clock. The three clocks will be the topic of my next post.

 

 

 

 

Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, and Rob North.

 

Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, and Slavko Radman.

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC Logo

 

My special thanks to Tipi.build tipi.build logo

 

My special thanks to Take Up code TakeUpCode 450 60

 

Seminars

I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Bookable (Online)

German

Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

  • C++ - The Core Language
  • C++ - The Standard Library
  • C++ - Compact
  • C++11 and C++14
  • Concurrency with Modern C++
  • Design Pattern and Architectural Pattern with C++
  • Embedded Programming with Modern C++
  • Generic Programming (Templates) with C++

New

  • Clean Code with Modern C++
  • C++20

Contact Me

Modernes C++,

RainerGrimmDunkelBlauSmall

 

Tags: Time

Comments   

0 #1 PhSucharee 2016-09-20 09:15
I think there is a typo. std::ratio should be a minute.
Quote
0 #2 Rainer Grimm 2016-09-20 16:21
Quoting PhSucharee:
I think there is a typo. std::ratio should be a minute.
Thanks. You are right. I fix it.
Quote
0 #3 accounting 101 2017-02-18 16:36
Keep this going please, great job!
Quote
0 #4 ivans 2021-09-29 13:30
You didn't emphasise that you use your own duration types with 'double' as a base type and not 'int' or 'long long' as default types defined in header. Default types cannot hold fractions and very hard to convert one into another without loosing precision.
Quote

Stay Informed about my Mentoring

 

Mentoring

English Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Course: The All-in-One Guide to C++20

Course: Master Software Design Patterns and Architecture in C++

Subscribe to the newsletter (+ pdf bundle)

All tags

Blog archive

Source Code

Visitors

Today 3700

Yesterday 4371

Week 39507

Month 169632

All 12057398

Currently are 146 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments