Skip to content

Commit c575b1d

Browse files
committed
docs: Add guide for measuring execution time in C++
1 parent a70ec58 commit c575b1d

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
---
2+
sidebar_position: 3
3+
title: Measuring Execution Time in C++
4+
sidebar_label: Measuring Execution Time in C++
5+
---
6+
7+
## Measuring Execution Time in C++
8+
9+
This simple example shows how to measure the execution time of a block of code using the `<chrono>` library.
10+
11+
### Code Example
12+
13+
```cpp
14+
// #include <chrono>
15+
16+
auto start = chrono::high_resolution_clock::now();
17+
18+
// CODE TO BE MEASURED
19+
// Example: for (int i = 0; i < 1000000; ++i) {}
20+
21+
auto end = chrono::high_resolution_clock::now();
22+
23+
chrono::duration<double, milli> duration = end - start;
24+
cout << "Execution time: " << duration.count() << " ms" << endl;
25+
```
26+
27+
### Explanation
28+
29+
* `chrono::high_resolution_clock::now()`
30+
Captures the current high-precision timestamp (start and end).
31+
32+
* `end - start`
33+
Calculates the elapsed time between the two timestamps.
34+
35+
* `chrono::duration<double, milli>`
36+
Converts the time difference into **milliseconds**.
37+
38+
* `duration.count()`
39+
Returns the numerical value of the elapsed time, which is printed to the console.
40+
41+
### Tip
42+
43+
You can replace the comment `// CODE TO BE MEASURED` with any operation you want to benchmark — for example, loops, function calls, or algorithm executions.

0 commit comments

Comments
 (0)