Measuring Elapsed Time with C++ Standard Library

You might want to measure the elapsed time to display the transfer speed or determine the remaining time for the heavy-weight processing to complete.

This article introduces a code sample that demonstrates how to measure elapsed time using the C++ Standard Library.

目次

Implementation Example

C++11 added many functions relating to time and date. Now, you can implement a process to measure elapsed time using just the C++ Standard Library without relying on native platform APIs.

You can use the Chrono library, part of the C++ Standard Library.

The following code measures the elapsed time taken by the something() function. It prints the result in milliseconds and seconds to the console.

#include <iostream>
#include <chrono>
#include <thread>

void something()
{
    // Sleep for 2.5 seconds
    std::this_thread::sleep_for(std::chrono::milliseconds(2500));
}

int main(int argc, const char * argv[])
{
    // Get the started time
    auto start = std::chrono::system_clock::now();
    
    // A process which you want to measure the elapsed time
    something();
    
    // Get the end time
    auto end = std::chrono::system_clock::now();
    
    // Calculate the difference (end - start) in milliseconds
    std::chrono::duration<double, std::milli> elapsed = end - start;
    
    // Calculate the difference (end - start) in seconds
    std::chrono::duration<double> elapsed2 = end - start;
    
    // Output the result into the console
    std::cout << elapsed.count() << "ms" << std::endl;
    std::cout << elapsed2.count() << "s" << std::endl;
    
    return 0;
}

When executed on my console, the output is as follows.

2504.99ms
2.505s

Get the current date and time

To obtain the current date and time, you can utilize the std::chrono::system_clock::now() method. Ensure you include the chrono header to access this method.

Sleep

The std::this_thread::sleep_for() method allows you to pause the current thread. This method is declared as follows. To utilize this method, make sure to include the thread header.

template< class Rep, class Period >
void sleep_for( const std::chrono::duration<Rep, Period>& sleep_duration );

This sleep duration can be specified as an argument using the type std::chrono::duration. As seen in the earlier example, a duration of 2500 milliseconds was specified, making the code intuitive. The following classes are defined to improve code readability.

  • std::chrono::nanoseconds
  • std::chrono::microseconds
  • std::chrono::milliseconds
  • std::chrono::seconds
  • std::chrono::minutes
  • std::chrono::hours
  • std::chrono::days (Since C++20)
  • std::chrono::weeks (Since C++20)
  • std::chrono::months (Since C++20)
  • std::chrono::years (Since C++20)

The first four classes are commonly used to specify sleep durations.

Calculate the Elapsed Time

Elapsed time refers to the duration a process takes to complete. It is calculated by determining the difference between the start and end times.

The result type of std::chrono::system_clock::now() method is the std::chrono::time_point<std::chrono::system_clock>. This type overrides the minus operator with the code using the C++ template, allowing you to determine the difference in any time unit by selecting the appropriate type.

Specifying the std::chrono::duration<double> returns the value in seconds. The count() method can retrieve the scalar value. The count() method returns a result type of double, as determined by the specified template argument.

Suppose you specify the std::chrono::duration<double, std::milli>. In that case, the method returns the value in milliseconds because you specify the std::milli to the template argument. The types possible to use as the elapsed time unit are the following.

  • std::nano
  • std::micro
  • std::milli

However, it’s crucial to consider the timer’s accuracy for minimal elapsed times. While a high-accuracy timer is recommended, this article does not delve into it.

著書紹介

Authored Books

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

Akira Hayashi (林 晃)のアバター Akira Hayashi (林 晃) Representative(代表), Software Engineer(ソフトウェアエンジニア)

アールケー開発代表。Appleプラットフォーム向けの開発を専門としているソフトウェアエンジニア。ソフトウェアの受託開発、技術書執筆、技術指導・セミナー講師。note, Medium, LinkedIn
-
Representative of RK Kaihatsu. Software Engineer Specializing in Development for the Apple Platform. Specializing in contract software development, technical writing, and serving as a tech workshop lecturer. note, Medium, LinkedIn

目次