Creating a timer in C++ can mean a few different things, depending on your needs:
Measuring Elapsed Time (Stopwatch): How long did a specific operation or block of code take?
One-Shot Delay (Blocking): Pause execution for a set amount of time.
Non-Blocking, One-Shot or Periodic Timer: Execute a function after a delay, or repeatedly at a fixed interval, without blocking the main program flow.
Let's explore each of these with C++ examples, using std::chrono for time manipulation, which is the standard and most precise way in modern C++.
1. Measuring Elapsed Time (Stopwatch)
This is useful for profiling code performance.
Concept: Record the time at the start, record it again at the end, and calculate the difference.
Tools:std::chrono::high_resolution_clock (or steady_clock for monotonic time), std::chrono::time_point, std::chrono::duration_cast.
cpp
#include <iostream>
#include <chrono> // For std::chrono
#include <thread> // For std::this_thread::sleep_for (to simulate work)
#include <numeric> // For std::accumulate
// --- Option A: Simple Inline Usage ---
void demonstrate_inline_stopwatch() {
std::cout << "--- Inline Stopwatch ---" << std::endl;
auto start_time = std::chrono::high_resolution_clock::now();
// Simulate some work
std::this_thread::sleep_for(std::chrono::milliseconds(150));
long long sum = 0;
for (int i = 0; i < 1000000; ++i) {
sum += i;
}
auto end_time = std::chrono::high_resolution_clock::now();
// Calculate duration
std::chrono::duration<double, std::milli> duration = end_time - start_time; // Duration in milliseconds (double precision)
std::cout << "Operation took " << duration.count() << " ms" << std::endl;
std::cout << "Sum: " << sum << std::endl; // To prevent compiler optimizing out the loop
}
// --- Option B: Encapsulate in a Class (Reusable Stopwatch) ---
class Stopwatch {
public:
Stopwatch() : m_start_time(std::chrono::high_resolution_clock::now()) {}
void reset() {
m_start_time = std::chrono::high_resolution_clock::now();
}
// Get elapsed time in milliseconds
double elapsed_milliseconds() const {
auto end_time = std::chrono::high_resolution_clock::now();
return std::chrono::duration<double, std::milli>(end_time - m_start_time).count();
}
// Get elapsed time in seconds
double elapsed_seconds() const {
auto end_time = std::chrono::high_resolution_clock::now();
return std::chrono::duration<double>(end_time - m_start_time).count(); // default unit is seconds
}
private:
std::chrono::high_resolution_clock::time_point m_start_time;
};
void demonstrate_stopwatch_class() {
std::cout << "\n--- Stopwatch Class ---" << std::endl;
Stopwatch sw; // Starts timing immediately
// Simulate some work
std::this_thread::sleep_for(std::chrono::milliseconds(250));
std::cout << "First work block elapsed: " << sw.elapsed_milliseconds() << " ms" << std::endl;
// Simulate more work (total time will accumulate)
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << "Total elapsed after second block: " << sw.elapsed_seconds() << " s" << std::endl;
// Reset and start timing a new operation
sw.reset();
std::this_thread::sleep_for(std::chrono::milliseconds(50));
std::cout << "New operation elapsed: " << sw.elapsed_milliseconds() << " ms" << std::endl;
}
int main() {
demonstrate_inline_stopwatch();
demonstrate_stopwatch_class();
return 0;
}
Explanation:
std::chrono::high_resolution_clock::now(): Gets the current time point with the highest available precision.
std::chrono::time_point: Represents a specific point in time.
std::chrono::duration: Represents a time interval. We can specify its underlying representation type (e.g., double) and its unit (e.g., std::milli for milliseconds, std::nano for nanoseconds, std::ratio<1> or just double for seconds).
Subtracting two time_points yields a duration.
.count() on a duration gives you the numeric value of that duration in its specified unit.
2. One-Shot Delay (Blocking)
This pauses the execution of the current thread for a specified duration.
Concept: Tell the operating system to put the current thread to sleep for X amount of time.
#include <iostream>
#include <thread> // For std::this_thread::sleep_for
#include <chrono> // For std::chrono::seconds, milliseconds etc.
void demonstrate_blocking_delay() {
std::cout << "\n--- Blocking Delay ---" << std::endl;
std::cout << "Starting blocking delay..." << std::endl;
// Pause execution for 2 seconds
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "2 seconds passed." << std::endl;
std::cout << "Waiting for 500 milliseconds..." << std::endl;
// Pause for 500 milliseconds
std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::cout << "500 milliseconds passed." << std::endl;
// You can also use explicit duration types
std::cout << "Waiting for 1.5 seconds..." << std::endl;
std::this_thread::sleep_for(std::chrono::duration<double>(1.5)); // 1.5 seconds
std::cout << "1.5 seconds passed." << std::endl;
}
int main() {
// ... (previous main content)
demonstrate_blocking_delay();
return 0;
}
Explanation:
std::this_thread::sleep_for(duration): The current thread will pause for at least the specified duration. The actual sleep time might be slightly longer due to OS scheduling.
std::chrono::seconds(2): Creates a duration object representing 2 seconds. You can use std::chrono::minutes, hours, milliseconds, microseconds, nanoseconds similarly.
3. Non-Blocking, One-Shot or Periodic Timer (Thread-Based)
This is more complex but allows your main program to continue running while the timer operates in the background. This is crucial for UI applications, games, or any event-driven system.
Concept:
A dedicated thread is created for the timer.
This thread waits for a specified interval using std::condition_variable::wait_for (which is interruptible).
After the interval (or if stopped), it executes a callback function.
For periodic timers, it loops this process.
A stop signal is needed to gracefully terminate the timer thread.
NonBlockingTimer Class: Encapsulates the timer logic.
_timer_thread: A std::thread object that will run the timer's logic in the background.
_interval: The time delay for each tick.
_callback: A std::function that holds the code to be executed when the timer ticks. This makes the timer flexible, allowing you to pass any function or lambda.
_should_stop (Atomic bool): This is a flag used to signal the timer thread to stop. std::atomic<bool> is used for thread-safe access to this flag from different threads.
_mutex and _cv (std::condition_variable): These are essential for managing thread synchronization and allowing the timer thread to "sleep" (wait) for a duration while being interruptible.
_cv.wait_for(lock, _interval, predicate): This is the core of the non-blocking timer. It waits for _interval or until the predicate (a lambda that checks _should_stop) returns true.
If _should_stop becomes true, wait_for returns true immediately (it's interrupted).
If the _interval expires, wait_for returns false.
start_one_shot() / start_periodic(): These methods create and launch the timer thread.
stop(): This method sets _should_stop to true and uses _cv.notify_one() to wake up the waiting timer thread. _timer_thread.join() then waits for the thread to finish its current loop iteration and terminate cleanly. It's crucial to join() a thread to ensure it completes its execution and its resources are released.
Destructor (~NonBlockingTimer()): Calling stop() in the destructor is vital. If the NonBlockingTimer object goes out of scope while its thread is still running, it would lead to a crash as the std::thread destructor would call std::terminate if join() or detach() hasn't been called.
How to Compile and Run:
Save the code (e.g., as timer_example.cpp) and compile using a C++11 compliant compiler (or newer, which is standard now):
(On Windows with MSVC, -std:c++17 or similar will do, and /EHsc is usually implicit for exceptions, no need for -pthread)
bash
./timer_example
#include <iostream>
#include <thread>
#include <chrono>
#include <functional> // For std::function
#include <condition_variable> // For std::condition_variable
#include <mutex> // For std::mutex
#include <atomic> // For std::atomic<bool>
// A non-blocking timer class
class NonBlockingTimer {
public:
// Constructor: Takes interval and a callback function
NonBlockingTimer(std::chrono::milliseconds interval, std::function<void()> callback)
: _interval(interval), _callback(callback), _should_stop(false) {}
// Destructor: Ensures the timer thread is stopped and joined
~NonBlockingTimer() {
stop(); // Ensure stop is called when timer object goes out of scope
}
// Starts the timer for a single shot
void start_one_shot() {
if (_timer_thread.joinable()) {
std::cerr << "Timer already running. Stop it first." << std::endl;
return;
}
_should_stop.store(false); // Ensure stop flag is false
_timer_thread = std::thread([this]() {
std::unique_lock<std::mutex> lock(_mutex);
// Wait for interval OR until _should_stop becomes true
if (_cv.wait_for(lock, _interval, [this]{ return _should_stop.load(); })) {
// Predicate was true, meaning stop was requested before timeout
// No callback needed.
} else {
// Timeout occurred (predicate was false), execute callback if not stopped
if (!_should_stop.load()) {
lock.unlock(); // Unlock mutex before calling callback (if callback is long)
_callback();
}
}
});
}
// Starts the timer to execute callback periodically
void start_periodic() {
if (_timer_thread.joinable()) {
std::cerr << "Timer already running. Stop it first." << std::endl;
return;
}
_should_stop.store(false); // Ensure stop flag is false
_timer_thread = std::thread([this]() {
while (!_should_stop.load()) {
std::unique_lock<std::mutex> lock(_mutex);
// Wait for interval OR until _should_stop becomes true
if (_cv.wait_for(lock, _interval, [this]{ return _should_stop.load(); })) {
// Predicate was true, meaning stop was requested. Exit loop.
break;
}
// If we reached here, it means timeout occurred (wait_for returned false)
// and _should_stop is still false, so execute callback.
if (!_should_stop.load()) {
lock.unlock(); // Unlock mutex before calling callback
_callback();
}
}
});
}
// Stops the timer thread
void stop() {
_should_stop.store(true); // Signal the thread to stop
_cv.notify_one(); // Wake up the waiting thread
if (_timer_thread.joinable()) {
_timer_thread.join(); // Wait for the thread to finish its current loop and terminate
}
}
private:
std::thread _timer_thread;
std::chrono::milliseconds _interval;
std::function<void()> _callback;
std::atomic<bool> _should_stop; // Atomic for thread-safe flag
std::condition_variable _cv;
std::mutex _mutex;
};
// Example usage of the NonBlockingTimer
int main() {
// ... (previous main content)
demonstrate_inline_stopwatch();
demonstrate_stopwatch_class();
demonstrate_blocking_delay();
std::cout << "\n--- Non-Blocking Timer ---" << std::endl;
int counter = 0;
// --- Periodic Timer Example ---
std::cout << "Starting periodic timer (every 500ms for 3 seconds)..." << std::endl;
NonBlockingTimer periodic_timer(std::chrono::milliseconds(500), [&]() {
std::cout << "Periodic tick! Counter: " << ++counter << std::endl;
});
periodic_timer.start_periodic();
// Main thread continues execution
std::this_thread::sleep_for(std::chrono::seconds(3)); // Let it run for 3 seconds
std::cout << "Main thread: Stopping periodic timer." << std::endl;
periodic_timer.stop(); // Stop the periodic timer
std::cout << "Periodic timer stopped. Final counter: " << counter << std::endl;
// --- One-Shot Timer Example ---
std::cout << "\nStarting one-shot timer (will fire in 2 seconds)..." << std::endl;
NonBlockingTimer one_shot_timer(std::chrono::seconds(2), []() {
std::cout << "One-shot timer fired after 2 seconds!" << std::endl;
});
one_shot_timer.start_one_shot();
std::cout << "Main thread: One-shot timer started, doing other work..." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(500)); // Main thread does something else
std::cout << "Main thread: Half a second passed." << std::endl;
// The one-shot timer will still fire around 2 seconds from its start,
// even though main thread slept for 0.5s and then exited.
// We add a small sleep to ensure the timer has time to fire before main exits.
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "Main thread finished." << std::endl;
return 0;
}