c-plus-plus
  1. c-plus-plus-stopwatch

C++ Programs: Stopwatch

Stopwatch is a simple program that can be used to measure the time taken by a certain process. This program can be helpful in performance analysis and testing.

Syntax

#include <chrono>

int main() {
    auto start = std::chrono::high_resolution_clock::now();
    // code to be measured
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
    // output duration
    return 0;
}

Example

#include <iostream>
#include <chrono>

using namespace std;

int main() {
    auto start = chrono::high_resolution_clock::now();

    int sum = 0;
    for(int i = 0; i < 1000000; i++) {
        sum += i;
    }

    auto end = chrono::high_resolution_clock::now();
    auto duration = chrono::duration_cast<chrono::milliseconds>(end - start);

    cout << "Time taken: " << duration.count() << " ms" << endl;

    return 0;
}

Output

Time taken: 2 ms

Explanation

In the above example, we have used the <chrono> library to measure the time taken by a loop. We start the stopwatch by capturing the current time using std::chrono::high_resolution_clock::now(). Then we run our loop, and when it is finished, we capture the end time. We can then calculate the time taken by subtracting the start time from the end time, and convert the duration to milliseconds using std::chrono::duration_cast<std::chrono::milliseconds>. Finally, we output the duration in ms.

Use

Stopwatch programs can be used to measure the time taken by different sections of code, and can help to identify performance bottlenecks and areas for improvement. They can be particularly useful when optimizing code for performance-critical applications, such as games or scientific simulations.

Important Points

  • The <chrono> library provides functions for measuring time in C++.
  • std::chrono::high_resolution_clock::now() is used to capture the current time.
  • std::chrono::duration_cast<std::chrono::milliseconds> can be used to convert the duration to milliseconds.
  • Stopwatch programs can be used to identify performance bottlenecks and areas for improvement.

Summary

Stopwatch programs are a useful tool for measuring the time taken by different sections of code. By using the <chrono> library, we can capture the current time, run our code, and then calculate the time taken. This can help to identify performance bottlenecks and areas for improvement in our programs.

Published on: