example4_simple_class.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <chrono>
#include <string>

class Timer {
private:
    std::chrono::time_point<std::chrono::steady_clock> start_time;
    std::string timer_name;

public:
    Timer(const std::string& name = "Timer") : timer_name(name) {
        start_time = std::chrono::steady_clock::now();
    }

    ~Timer() {
        auto end_time = std::chrono::steady_clock::now();
        auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time);
        std::cout << timer_name << " took " << duration.count() << " microseconds" << std::endl;
    }
};

void some_function() {
    Timer t("some_function");
    // Simulate some work
    for (int i = 0; i < 1000000; ++i) {
        int x = i * i;
    }
}

int main() {
    Timer t("main");
    some_function();
    return 0;
}
Back to timers