C++ Chrono Complete Guide | 'Time' Library Complete Guide

C++ Chrono Complete Guide | 'Time' Library Complete Guide

이 글의 핵심

Summarizes core concepts and practical points of C++ Chrono Complete Guide.

Basic Usage

Here is detailed implementation code using C++. Import the necessary modules and process data with loops. Understand the role of each part while examining the code.

#include <chrono>
#include <iostream>
using namespace std;
using namespace chrono;

int main() {
    // Time measurement
    auto start = high_resolution_clock::now();
    
    // Work
    for (int i = 0; i < 1000000; i++) {
        // ...
    }
    
    auto end = high_resolution_clock::now();
    
    // Elapsed time
    auto duration = duration_cast<milliseconds>(end - start);
    cout << "Time: " << duration.count() << "ms" << endl;
}

Duration

Below is an implementation example using C++. Understand the role of each part while examining the code.

// Various units
seconds sec(5);
milliseconds ms(5000);
microseconds us(5000000);
nanoseconds ns(5000000000);

// Conversion
auto ms2 = duration_cast<milliseconds>(sec);
cout << ms2.count() << "ms" << endl;  // 5000

// Arithmetic operations
auto total = 1s + 500ms;  // 1500ms
auto half = 1s / 2;       // 500ms

Time Point

Below is an implementation example using C++. Understand the role of each part while examining the code.

// Current time
auto now = system_clock::now();

// Add time
auto future = now + hours(24);

// Subtract time
auto past = now - minutes(30);

// Time difference
auto diff = future - now;
cout << duration_cast<hours>(diff).count() << " hours" << endl;

Practical Examples

Example 1: Benchmark

Here is detailed implementation code using C++. Process data with loops. Understand the role of each part while examining the code.

template<typename Func>
void benchmark(const string& name, Func func) {
    auto start = high_resolution_clock::now();
    
    func();
    
    auto end = high_resolution_clock::now();
    auto duration = duration_cast<microseconds>(end - start);
    
    cout << name << ": " << duration.count() << "μs" << endl;
}

int main() {
    benchmark("vector push_back", [] {
        vector<int> v;
        for (int i = 0; i < 10000; i++) {
            v.push_back(i);
        }
    });
    
    benchmark("vector reserve", [] {
        vector<int> v;
        v.reserve(10000);
        for (int i = 0; i < 10000; i++) {
            v.push_back(i);
        }
    });
}

Example 2: Timer

Here is detailed implementation code using C++. Define a class to encapsulate data and functionality, and process data with loops. Understand the role of each part while examining the code.

class Timer {
private:
    time_point<high_resolution_clock> start;
    
public:
    Timer() : start(high_resolution_clock::now()) {}
    
    void reset() {
        start = high_resolution_clock::now();
    }
    
    double elapsed() const {
        auto end = high_resolution_clock::now();
        auto duration = duration_cast<milliseconds>(end - start);
        return duration.count();
    }
    
    void print(const string& msg) const {
        cout << msg << ": " << elapsed() << "ms" << endl;
    }
};

int main() {
    Timer timer;
    
    // Task 1
    this_thread::sleep_for(100ms);
    timer.print("Task 1");
    
    // Task 2
    this_thread::sleep_for(200ms);
    timer.print("Task 2");
}

Example 3: Timeout

Here is detailed implementation code using C++. Process data with loops and perform branching with conditionals. Understand the role of each part while examining the code.

bool waitForCondition(function<bool()> condition, milliseconds timeout) {
    auto start = steady_clock::now();
    
    while (!condition()) {
        auto now = steady_clock::now();
        if (now - start > timeout) {
            return false;  // Timeout
        }
        
        this_thread::sleep_for(10ms);
    }
    
    return true;  // Success
}

int main() {
    bool ready = false;
    
    thread worker([&]() {
        this_thread::sleep_for(500ms);
        ready = true;
    });
    
    if (waitForCondition([&]() { return ready; }, 1s)) {
        cout << "Complete" << endl;
    } else {
        cout << "Timeout" << endl;
    }
    
    worker.join();
}

Example 4: Frame Rate Control

Here is detailed implementation code using C++. Define a class to encapsulate data and functionality, process data with loops, and perform branching with conditionals. Understand the role of each part while examining the code.

class FrameRateController {
private:
    duration<double> targetFrameTime;
    time_point<steady_clock> lastFrame;
    
public:
    FrameRateController(int fps) 
        : targetFrameTime(1.0 / fps),
          lastFrame(steady_clock::now()) {}
    
    void wait() {
        auto now = steady_clock::now();
        auto elapsed = now - lastFrame;
        
        if (elapsed < targetFrameTime) {
            this_thread::sleep_for(targetFrameTime - elapsed);
        }
        
        lastFrame = steady_clock::now();
    }
    
    double getFPS() const {
        auto now = steady_clock::now();
        auto elapsed = duration_cast<duration<double>>(now - lastFrame);
        return 1.0 / elapsed.count();
    }
};

int main() {
    FrameRateController frc(60);  // 60 FPS
    
    for (int i = 0; i < 600; i++) {
        // Game logic
        
        frc.wait();
        
        if (i % 60 == 0) {
            cout << "FPS: " << frc.getFPS() << endl;
        }
    }
}

Clock Types

Below is an implementation example using C++. Try running the code directly to check its operation.

// system_clock: system time (adjustable)
auto sys = system_clock::now();

// steady_clock: monotonic (for timer)
auto steady = steady_clock::now();

// high_resolution_clock: highest precision
auto high = high_resolution_clock::now();

Time Conversion

Below is an implementation example using C++. Understand the role of each part while examining the code.

// Convert to time_t
auto now = system_clock::now();
time_t tt = system_clock::to_time_t(now);

// Output
cout << ctime(&tt) << endl;

// Convert from time_t
time_t tt2 = time(0);
auto tp = system_clock::from_time_t(tt2);

Literals (C++14)

Below is an implementation example using C++. Import the necessary modules and try running the code directly to check its operation.

using namespace chrono_literals;

auto d1 = 5s;       // 5 seconds
auto d2 = 100ms;    // 100 milliseconds
auto d3 = 2min;     // 2 minutes
auto d4 = 1h;       // 1 hour

auto total = 1h + 30min + 45s;
cout << duration_cast<seconds>(total).count() << " seconds" << endl;

Common Issues

Issue 1: Clock Selection

Below is an implementation example using C++. Understand the role of each part while examining the code.

// ❌ system_clock (problem when time is adjusted)
auto start = system_clock::now();
// System time changed
auto end = system_clock::now();
// Negative duration possible!

// ✅ steady_clock (for timer)
auto start = steady_clock::now();
// ...
auto end = steady_clock::now();
// Always positive

Issue 2: duration_cast Loss

Below is an implementation example using C++. Understand the role of each part while examining the code.

// ❌ Precision loss
auto ns = 1500ns;
auto ms = duration_cast<milliseconds>(ns);
cout << ms.count() << endl;  // 1 (500ns loss)

// ✅ Aware of loss
auto ns = 1500ns;
auto ms = duration_cast<milliseconds>(ns);
auto remainder = ns - ms;
cout << ms.count() << "ms + " << remainder.count() << "ns" << endl;

Issue 3: Overflow

Below is an implementation example using C++. Try running the code directly to check its operation.

// ❌ Overflow
auto big = hours(INT_MAX);
auto bigger = big + hours(1);  // Overflow

// ✅ Appropriate type
auto big = duration<long long, ratio<3600>>(INT_MAX);

Performance Measurement

Here is detailed implementation code using C++. Define a class to encapsulate data and functionality, and process data with loops. Understand the role of each part while examining the code.

class Profiler {
private:
    map<string, duration<double>> timings;
    time_point<high_resolution_clock> start;
    string currentSection;
    
public:
    void begin(const string& section) {
        currentSection = section;
        start = high_resolution_clock::now();
    }
    
    void end() {
        auto end = high_resolution_clock::now();
        timings[currentSection] += duration_cast<duration<double>>(end - start);
    }
    
    void report() {
        for (const auto& [section, time] : timings) {
            cout << section << ": " << time.count() << "s" << endl;
        }
    }
};

int main() {
    Profiler profiler;
    
    profiler.begin("Initialization");
    this_thread::sleep_for(100ms);
    profiler.end();
    
    profiler.begin("Processing");
    this_thread::sleep_for(200ms);
    profiler.end();
    
    profiler.report();
}

FAQ

Q1: When to use chrono?

A:

  • Time measurement
  • Timer
  • Benchmark
  • Frame rate control

Q2: Which clock to use?

A:

  • steady_clock: Timer, benchmark
  • system_clock: Real time
  • high_resolution_clock: Highest precision

Q3: Performance overhead?

A: Very minimal. About one system call.

Q4: Precision?

A: Platform-dependent but usually nanosecond level.

Q5: Thread-safe?

A: now() calls are safe.

Q6: Chrono learning resources?

A:

  • cppreference.com
  • “C++11/14/17 Features”
  • “The C++ Standard Library”

Other articles connected to this topic.