chrono

Need to better understand how std::chrono works, since there are many different implementations it seems. std::chrono in C++ provides tools for time-related functions. It has three main concepts:

  1. Duration
  2. Time point
  3. Clock

1. Duration

  1. Duration: Represents a time span or interval. It’s a count of ticks with a specific time unit (seconds, milliseconds, etc.).

The type std::chrono::duration is templated and can represent time in any units, not just seconds.

std::chrono::seconds s(10); // 10 seconds
std::chrono::duration<Rep, Period>

2. Time Point

  1. Time Point: A specific point in time relative to a clock.
std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();

Time point

std::chrono::time_point<Clock, Duration>

3. Clock

  1. Clock: Tracks current time. Three common types:
    • system_clock: Wall clock, can be converted to/from time_t (system time).
    • steady_clock: Monotonic clock, always moves forward.
    • high_resolution_clock: Provides highest resolution, often alias of one of the above.

System clock vs steady clock?

  • Steady clock represents a monotonic clock that never goes backward. Once the clock starts, it continues ticking without adjustments for system time changes or drift.

The steady clock is best for measuring time interval. Source: https://stackoverflow.com/questions/31552193/difference-between-steady-clock-vs-system-clock

Also see ROS Clock.

Example

#include <iostream>
#include <chrono>
#include <thread>
 
int main() {
    // Record the start time using steady_clock (a monotonic clock)
    std::chrono::time_point<std::chrono::steady_clock> start = std::chrono::steady_clock::now();
    
    // Create a duration of 2 seconds
    std::chrono::duration<int> two_seconds(2);
 
    // Sleep for 2 seconds
    std::this_thread::sleep_for(two_seconds);
 
    // Record the end time
    std::chrono::time_point<std::chrono::steady_clock> end = std::chrono::steady_clock::now();
 
    // Calculate the elapsed time as a duration
    std::chrono::duration<double> elapsed = end - start;
 
    // Output the duration in seconds
    std::cout << "Elapsed time: " << elapsed.count() << " seconds\n";
 
    return 0;
}