timeSinceEpoch

Time Duration

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.

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (open)
  • "Generic Programming (Templates) with C++": October 2024
  • "Embedded Programming with Modern C++": October 2024
  • "Clean Code: Best Practices for Modern C++": March 2025
  • Do you want to stay informed: Subscribe.

     

     

     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.

    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, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, 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, Stephen Kelley, Kyle Dean, Tusar Palauri, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery, Matt Godbolt, and Honey Sukesan.

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

    My special thanks to Embarcadero
    My special thanks to PVS-Studio
    My special thanks to Tipi.build 
    My special thanks to Take Up Code
    My special thanks to SHAVEDYAKS

    Modernes C++ GmbH

    Modernes C++ Mentoring (English)

    Do you want to stay informed about my mentoring programs? Subscribe Here

    Rainer Grimm
    Yalovastraße 20
    72108 Rottenburg

    Mobil: +49 176 5506 5086
    Mail: schulung@ModernesCpp.de
    Mentoring: www.ModernesCpp.org

    Modernes C++ Mentoring,

     

     

    0 replies

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply

    Your email address will not be published. Required fields are marked *