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
  • DSA Tutorial
  • Data Structures
  • Algorithms
  • Array
  • Strings
  • Linked List
  • Stack
  • Queue
  • Tree
  • Graph
  • Searching
  • Sorting
  • Recursion
  • Dynamic Programming
  • Binary Tree
  • Binary Search Tree
  • Heap
  • Hashing
  • Divide & Conquer
  • Mathematical
  • Geometric
  • Bitwise
  • Greedy
  • Backtracking
  • Branch and Bound
  • Matrix
  • Pattern Searching
  • Randomized
Open In App
Next Article:
Find Exclusive Time of Functions
Next article icon

Measure execution time of a function in C++

Last Updated : 11 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We can find out the time taken by different parts of a program by using the std::chrono library introduced in C++ 11. We have discussed at How to measure time taken by a program in C. The functions described there are supported in C++ too but they are C specific. For clean and robust C++ programs we should strive to use C++ specific language constructs only.
std::chrono has two distinct objects–timepoint and duration. A timepoint as the name suggests represents a point in time whereas a duration represents an interval or span of time. The C++ library allows us to subtract two timepoints to get the interval of time passed in between. Using provided methods we can also convert this duration to appropriate units.
The std::chrono provides us with three clocks with varying accuracy. The high_resolution_clock is the most accurate and hence it is used to measure execution time.
Step 1: Get the timepoint before the function is called
 

CPP
#include <chrono> using namespace std::chrono;  // Use auto keyword to avoid typing long // type definitions to get the timepoint // at this instant use function now() auto start = high_resolution_clock::now(); 

Step 2: Get the timepoint after the function is called 
 

CPP
#include <chrono> using namespace std::chrono;  // After function call auto stop = high_resolution_clock::now(); 

Step 3: Get the difference in timepoints and cast it to required units 
 

CPP
// Subtract stop and start timepoints and // cast it to required unit. Predefined units // are nanoseconds, microseconds, milliseconds, // seconds, minutes, hours. Use duration_cast() // function. auto duration = duration_cast<microseconds>(stop - start);  // To get the value of duration use the count() // member function on the duration object cout << duration.count() << endl; 

A complete C++ program demonstrating the procedure is given below. We fill up a vector with some random numbers and measure the time taken by sort() function to sort this vector.
 

CPP
// C++ program to find out execution time of // of functions #include <algorithm> #include <chrono> #include <iostream> #include<vector> using namespace std; using namespace std::chrono;  // For demonstration purpose, we will fill up // a vector with random integers and then sort // them using sort function. We fill record // and print the time required by sort function int main() {      vector<int> values(10000);      // Generate Random values     auto f = []() -> int { return rand() % 10000; };      // Fill up the vector     generate(values.begin(), values.end(), f);      // Get starting timepoint     auto start = high_resolution_clock::now();      // Call the function, here sort()     sort(values.begin(), values.end());      // Get ending timepoint     auto stop = high_resolution_clock::now();      // Get duration. Substart timepoints to      // get duration. To cast it to proper unit     // use duration cast method     auto duration = duration_cast<microseconds>(stop - start);      cout << "Time taken by function: "          << duration.count() << " microseconds" << endl;      return 0; } 

Output: (Machine Dependent) 
 

Time taken by function: 3062 microseconds

The time complexity of the sort() function is O(n log n), where n is the number of elements in the vector. Therefore, the time complexity of this program is also O(n log n), since it measures the execution time of the sort() function. 

The space complexity of this program is O(n), since it creates a vector of size n to store the random integers.


References 
https://www.geeksforgeeks.org/chrono-in-c/
 



Next Article
Find Exclusive Time of Functions

S

Sayan Mahapatra
Improve
Article Tags :
  • C++
  • Competitive Programming
  • DSA
  • CPP-Library
  • cpp-puzzle
Practice Tags :
  • CPP

Similar Reads

  • strftime() function in C/C++
    strftime() is a function in C which is used to format date and time. It comes under the header file time.h, which also contains a structure named struct tm which is used to hold the time and date. The syntax of strftime() is as shown below : size_t strftime(char *s, size_t max, const char *format, c
    3 min read
  • Find Exclusive Time of Functions
    Given a list logs, where logs[i] represents the ith log message formatted as a string "{function_id}:{"start" | "end"}:{timestamp}". For example, "0:start:3" means a function call with function ID 0 started at the beginning of timestamp 3, and "1:end:2" means a function call with function ID 1 ended
    5 min read
  • map count() Function in C++ STL
    The std::map::count() in C++ is a built-in function that is used to count the occurrence of the given key in the map container. It is the member function of the std::map container. In this article, we will learn how to use std::map::count() in C++. Syntaxmp.count(key) Parameters key: The value whose
    2 min read
  • multiset count() function in C++ STL
    The multiset::count() function is a built-in function in C++ STL that searches for a specific element in the multiset container and returns the number of occurrences of that element. Syntax: multiset_name.count(val) Parameters: The function accepts a single parameter val which specifies the element
    2 min read
  • How to Measure Elapsed Time in C++?
    Measuring elapsed time is a common requirement for most software development packages. It is used to determine the efficiency of the program and gives an idea of which parts of the program takes which much time. This helps in optimizing the code, such that improves its execution time. In this articl
    3 min read
  • unordered_multimap count() function in C++ STL
    The unordered_multimap::count() is a built-in function in C++ STL that returns the number of elements in the container whose key is equal to the key passed in the parameter. Syntax: unordered_multimap_name.count(key) Parameters: The function accepts a single mandatory parameter key that specifies th
    2 min read
  • unordered_multiset count() function in C++ STL
    The unordered_multiset::count() is a built-in function in C++ STL which returns the count of elements in the unordered_multiset container which is equal to a given value. Syntax: unordered_multiset_name.count(val) Parameters: The function accepts a single mandatory parameter val which specifies the
    2 min read
  • tan() function for complex number in C++
    The tan() function for complex numbers is defined in the complex header file. This function is the complex version of the tan() function. This function is used to calculate the complex tan of the complex number z. This function returns the tan of complex number z. Syntax: tan(z); Parameter: z: This
    2 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
  • localtime() function in C++
    The localtime() function is defined in the ctime header file. The localtime() function converts the given time since epoch to calendar time which is expressed as local time. Syntax: tm* localtime(const time_t* time_ptr); Parameter: This function accepts a parameter time_ptr which represents the poin
    1 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