Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
log() Function in C++
Next article icon

Chrono in C++

Last Updated : 20 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

<chrono> is a C++ header that provides a collection of types and functions to work with time. It is a part of the C++ Standard Template Library (STL) and it’s included in C++11 and later versions.

<chrono> provides three main types of clocks: system_clock, steady_clock, and high_resolution_clock. These clocks are used to measure time in various ways.

system_clock represents the system-wide real time wall clock. It’s affected by the system’s time adjustments.
steady_clock represents a monotonically increasing clock that’s not affected by changes to the system time.
high_resolution_clock is the clock with the shortest tick period available on the system.

<chrono> also provides a collection of duration types, including duration<Rep, Period>, that can be used to represent a duration of time. Rep is the representation type (such as int or long) and Period is the ratio of the duration (such as nanoseconds or seconds).
Additionally, <chrono> provides a collection of time point types, including time_point<Clock, Duration>, that can be used to represent a point in time. Clock is the clock type (such as system_clock) and Duration is the duration type (such as seconds)

Chrono library is used to deal with date and time. This library was designed to deal with the fact that timers and clocks might be different on different systems and thus to improve over time in terms of precision. The unique thing about chrono is that it provides a precision-neutral concept by separating duration and point of time (“timepoint”) from specific clocks. chrono is the name of a header and also of a sub-namespace: All the elements in this header (except for the common_type specializations) are not defined directly under the std namespace (like most of the standard library) but under the std::chrono namespace. The elements in this header deal with time. This is done mainly by means of three concepts:

Duration

A duration object expresses a time span by means of a count like a minute, two hours, or ten milliseconds. For example, “42 seconds” could be represented by a duration consisting of 42 ticks of a 1-second time unit. 

CPP




// C++ program to illustrate the utility
// function duration::count
#include <iostream>   
#include <chrono>    
 
int main ()
{
    using namespace std::chrono;
    // std::chrono::milliseconds is an
    // instantiation of std::chrono::duration:- 1 second
    milliseconds mil(1000);
     
    mil = mil*60;
     
    std::cout << "duration (in periods): ";
    std::cout << mil.count() << " milliseconds.\n";
     
    std::cout << "duration (in seconds): ";
    std::cout << (mil.count() * milliseconds::period::num /
                               milliseconds::period::den);
    std::cout << " seconds.\n";
 
    return 0;
}
 
 

Output:

duration (in periods): 60000 milliseconds. duration (in seconds): 60 seconds.

Clock

A clock consists of a starting point (or epoch) and a tick rate. For example, a clock may have an epoch of February 22, 1996 and tick every second. C++ defines three clock types:

  • system_clock-It is the current time according to the system (regular clock which we see on the toolbar of the computer). It is written as- std::chrono::system_clock
  • steady_clock-It is a monotonic clock that will never be adjusted.It goes at a uniform rate. It is written as- std::chrono::steady_clock
  • high_resolution_clock– It provides the smallest possible tick period. It is written as-std::chrono::high_resolution_clock

Time point

A time_point object expresses a point in time relative to a clock’s epoch. Internally, the object stores an object of a duration type, and uses the Clock type as a reference for its epoch.  

CPP




// C++ program to illustrate time point
// and system clock functions
#include <iostream>
#include <chrono>
#include <ctime>
 
// Function to calculate
// Fibonacci series
long fibonacci(unsigned n)
{
    if (n < 2) return n;
    return fibonacci(n-1) + fibonacci(n-2);
}
 
int main()
{
    // Using time point and system_clock
    std::chrono::time_point<std::chrono::system_clock> start, end;
 
    start = std::chrono::system_clock::now();
    std::cout << "f(42) = " << fibonacci(42) << '\n';
    end = std::chrono::system_clock::now();
 
    std::chrono::duration<double> elapsed_seconds = end - start;
    std::time_t end_time = std::chrono::system_clock::to_time_t(end);
 
    std::cout << "finished computation at " << std::ctime(&end_time)
              << "elapsed time: " << elapsed_seconds.count() << "s\n";
}
 
 

Output:

f(42) = 267914296 finished computation at Wed Jan  4 05:13:48 2017 elapsed time: 2.14538s

It’s important to note that the precision and accuracy of the clocks and durations provided by <chrono> may vary depending on the system and platform, and it’s always a good idea to check the documentation of your platform for more information.



Next Article
log() Function in C++

S

Shambhavi Singh
Improve
Article Tags :
  • C++
  • CPP-Library
Practice Tags :
  • CPP

Similar Reads

  • cout in C++
    In C++, cout is an object of the ostream class that is used to display output to the standard output device, usually the monitor. It is associated with the standard C output stream stdout. The insertion operator (<<) is used with cout to insert data into the output stream. Let's take a look at
    2 min read
  • std::function in C++
    The std::function() in C++ is a function wrapper class which can store and call any function or a callable object. In this article, we will learn about std::function in C++ and how to use it in different cases. Table of Content What is std::function in C++?Example of std::functionMember Functions of
    6 min read
  • log() Function in C++
    The std::log() in C++ is a built-in function that is used to calculate the natural logarithm (base e) of a given number. The number can be of any data type i.e. int, double, float, long long. It is defined inside the <cmath> header file. In this article we will learn about how to use std::log(
    2 min read
  • Copy Elision in C++
    Copy elision (also known as copy omission) is a compiler optimization method that prevents objects from being duplicated or copied. It makes 'returning by value' or 'pass-by-value' feasible in practice. In simple terms, the compiler prevents the making of extra copies which results in saving space a
    4 min read
  • Naming Convention in C++
    Naming a file or a variable is the first and the very basic step that a programmer takes to write clean codes, where naming has to be appropriate so that for any other programmer it acts as an easy way to read the code. In C++, naming conventions are the set of rules for choosing the valid name for
    6 min read
  • cosh() function in C++ STL
    The cosh() is an inbuilt function in C++ STL which returns the hyperbolic cosine of an angle given in radians. Syntax : cosh(data_type x) Parameter :The function accepts one mandatory parameter x which specifies the hyperbolic angle in radian. The parameter can be of double, float or long double dat
    2 min read
  • strol() function in C++
    The strtol() function in C++ interprets the contents of a string as an integral number of the specified base and return its value as a long int.This function also sets an end pointer that points to the first character after the last valid numeric character of the string, if there is no such characte
    3 min read
  • wcschr() function in C++
    wcschr() function in C++ searches for the first occurrence of a wide character in a wide string. The terminating null wide character is considered part of the string. Therefore, it can also be located in order to retrieve a pointer to the end of a wide string. Syntax: const wchar_t* wcschr (const wc
    2 min read
  • scalbn() function in C++
    The scalbn() function is defined in the cmath header file. This function is used to calculate the product of given number x and FLT_RADIX raised to the power n. Syntax:- float scalbn(float x, int n); or double scalbn(double x, int n); or long double scalbn(long double x, int n); or double scalbn(int
    2 min read
  • Strings in C++
    In C++, strings are sequences of characters that are used to store words and text. They are also used to store data, such as numbers and other types of information in the form of text. Strings are provided by <string> header file in the form of std::string class. Creating a StringCreating a st
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences