DigestCPP

Lets Understand With Example

  • Home
  • Design Principal
  • Design Patterns
  • C++ 11 Features
  • C++11 Multithreading
  • Contact Us

time c++11

time

In C++11, all time related classes are present in “#include<chrono>” under the namespace “std::chrono”. There are three main parts:

  • duration (period of time like 5 seconds orĀ  10 seconds and in other word its difference between two time_points)
  • time_point (given point in time, current time point will get from clock now, current tp = steady_clock::now())
  • clock (It is clock, can be wall clock or monotonic (cannot reset)

duration: In technical, it is class template, it gives the time between two points in time.

time_point: In technical, it is class template, it represents a point in time of given epoch.

clock: There are three clocks:

  • system_clock (wall clock, can reset it)
  • steady_clock (cannot reset it, its monotonic clock)
  • high_resolution_clock (a clock with shortest time increment present on system)

source code with example:

/*
Program: Time 
Author: Alpha Master
Date: 14 March 2021
*/

//Header File
#include<iostream>
#include<chrono>
#include<thread>

int main()
{
    //duration
    std::cout<<"Time"<<std::endl;
    //First reading
    auto t1 = std::chrono::steady_clock::now();

    auto tp0 = std::chrono::time_point_cast<std::chrono::seconds>(t1).time_since_epoch().count();
    std::cout<<"time point in seconds, converted from epoch:"<<tp0<<std::endl;

    std::this_thread::sleep_for (std::chrono::seconds(5));

    //Second Reading
    auto t2 = std::chrono::steady_clock::now();
    auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1);
    std::cout<<"duration in milliseconds:"<<diff.count()<<"ms"<<std::endl;

    //Time point
    auto tp2 = std::chrono::time_point_cast<std::chrono::seconds>(t2).time_since_epoch().count();
    std::cout<<"time point in seconds, converted from epoch:"<<tp2<<std::endl;

    //clock
    std::chrono::time_point<std::chrono::system_clock> tp3= std::chrono::system_clock::now();
    time_t mytime = std::chrono::system_clock::to_time_t(tp3);
    printf("%s", asctime(gmtime(&mytime)));

    return 0;
}

Output:

Time
time point in seconds, converted from epoch:10361
duration in milliseconds:5000ms
time point in seconds, converted from epoch:10366
Sun Mar 14 10:25:51 2021

Primary Sidebar




DigestCPP © 2023. All rights reserved.

    About Privacy Policy Terms and Conditions Contact Us Disclaimer