Of course! Querying time and ticks in Windows C++ is a common task, but choosing the right tool is crucial as they have very different characteristics. The methods generally fall into two categories:
Interval Timers: For measuring performance, elapsed time, and animation. These should be high-resolution and monotonic (they only ever move forward and aren't affected by system time changes).
Wall-Clock Timers: For getting the current date and time. These are for timestamps, logging, and scheduling. They are not monotonic and can jump backward or forward if the user or a service changes the system clock.
Here are the most common ways to query time in Windows C++, with their pros and cons.
This is the standard C++11 (and later) way to handle high-performance timing. It's a library feature, not a direct OS call, but on Windows, it's implemented using the best available OS mechanism.
On Microsoft's Visual C++ compiler (MSVC), std::chrono::high_resolution_clock is a typedef for std::chrono::steady_clock, which uses QueryPerformanceCounter internally.
cpp
#include <iostream>
#include <chrono>
#include <thread> // for std::this_thread::sleep_for
void do_work() {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
int main() {
// Get the starting time point
auto start = std::chrono::high_resolution_clock::now();
// Perform some work
do_work();
// Get the ending time point
auto end = std::chrono::high_resolution_clock::now();
// Calculate the duration
std::chrono::duration<double, std::milli> elapsed_ms = end - start;
auto elapsed_us = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
std::cout << "Elapsed time: " << elapsed_ms.count() << " ms\n";
std::cout << "Elapsed time: " << elapsed_us.count() << " us\n";
return 0;
}
Pros:
Portable: This is standard C++ code that will work on other platforms like Linux and macOS.
Type-Safe: The library uses duration and time_point types, preventing errors from mixing units (e.g., adding milliseconds to seconds by mistake).
Easy to Use: The syntax is clean, expressive, and handles unit conversions for you (e.g., duration_cast).
High-Resolution and Monotonic: On Windows, it leverages QueryPerformanceCounter, giving you the best of both worlds.
Cons:
Abstraction Overhead: There might be a minuscule performance overhead compared to calling the WinAPI functions directly, but it's almost always negligible and worth the safety and portability.
Best For:
Almost all new C++ applications. This should be your default choice for measuring time intervals.
2. QueryPerformanceCounter (The WinAPI Gold Standard for Intervals)
This is the underlying high-resolution timer that std::chrono uses on Windows. It queries a hardware counter. You must also query its frequency to convert the "ticks" into seconds.
cpp
#include <iostream>
#include <Windows.h>
void do_work() {
Sleep(50); // Windows-specific sleep
}
int main() {
LARGE_INTEGER frequency;
LARGE_INTEGER start;
LARGE_INTEGER end;
// Get the frequency of the performance counter.
// This needs to be done only once.
QueryPerformanceFrequency(&frequency);
// Get the starting tick count
QueryPerformanceCounter(&start);
// Perform some work
do_work();
// Get the ending tick count
QueryPerformanceCounter(&end);
// Calculate the elapsed time in milliseconds
double elapsed_ms = static_cast<double>(end.QuadPart - start.QuadPart) * 1000.0 / frequency.QuadPart;
std::cout << "Elapsed time: " << elapsed_ms << " ms\n";
return 0;
}
Pros:
Highest Resolution: This is typically the most precise timer available on the system (often sub-microsecond).
Monotonic: It is not affected by changes to the system clock, making it ideal for performance measurements.
The Standard: It's the de-facto standard for high-performance timing in Windows games and applications.
Cons:
More Complex: You have to manage the frequency and perform the conversion math yourself. It's easy to make a mistake with integer division or floating-point precision.
Windows-Specific: This code is not portable.
Best For:
C-style or legacy C++ Windows projects where std::chrono is not available or desired.
Situations where you need to be absolutely certain you're using the WinAPI directly.
3. GetTickCount64 (Low-Resolution Intervals)
This function retrieves the number of milliseconds that have elapsed since the system was started.
Very Simple: Extremely easy to use; just call and subtract.
Monotonic: Like QPC, it's based on system uptime, not the wall-clock.
No Wraparound Issues: The 64-bit value will not wrap around for an impossibly long time (hundreds of millions of years), fixing the major flaw of its predecessor, GetTickCount.
Cons:
Low Resolution: The resolution is typically between 10 and 16 milliseconds. It is not suitable for measuring fast operations. An operation taking 2 ms might be reported as 0 ms or 15 ms.
Best For:
Measuring long-running tasks where millisecond precision is sufficient (e.g., timeouts, checking if several seconds have passed).
4. GetSystemTimeAsFileTime (Wall-Clock Time)
This function gets the current date and time as a FILETIME structure, which represents the number of 100-nanosecond intervals since January 1, 1601 (UTC).
cpp
#include <iostream>
#include <Windows.h>
int main() {
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
// The FILETIME structure is not easy to use directly.
// It's often converted to a ULARGE_INTEGER to access the 64-bit value.
ULARGE_INTEGER uli;
uli.LowPart = ft.dwLowDateTime;
uli.HighPart = ft.dwHighDateTime;
// This value represents 100-nanosecond intervals since 1601.
std::cout << "Timestamp (100-ns intervals): " << uli.QuadPart << std::endl;
// You can also convert it to a more human-readable format
SYSTEMTIME st;
FileTimeToSystemTime(&ft, &st);
std::cout << "Current UTC time: " << st.wHour << ":" << st.wMinute << ":" << st.wSecond << "\n";
return 0;
}
Pros:
High Resolution: The unit is 100-nanoseconds, which is very precise.
Provides UTC Time: Gives the actual coordinated universal time, which is essential for logging and creating universal timestamps.
Cons:
NOT MONOTONIC: This is its biggest drawback for interval timing. If the user changes the system clock or an NTP service syncs it, the time can jump forwards or backwards, making any interval measurement based on it completely invalid.
Awkward to Use: The FILETIME struct requires conversion to be used for arithmetic or display.
Best For:
Creating timestamps for log files, events, or file creation/modification times. Do not use it for measuring performance.
Summary Table
Function
Best For
Resolution
Monotonic?
Portability
Ease of Use
std::chrono
Most new code
High (uses QPC)
Yes
Excellent (C++)
Excellent
QueryPerformanceCounter
High-perf intervals (C-style)
Highest
Yes
Windows-only
Moderate
GetTickCount64
Long timeouts, simple intervals
Low (~15 ms)
Yes
Windows-only
Excellent
GetSystemTimeAsFileTime
Timestamps, logging
High (100 ns)
No
Windows-only
Awkward
GetTickCount (Legacy)
Avoid in new code
Low (~15 ms)
Yes
Windows-only
Simple
Final Recommendation
For performance measurement, game loops, or any interval timing: Use std::chrono::high_resolution_clock. It gives you the power of QueryPerformanceCounter with the safety and portability of the C++ standard library.
For creating timestamps: Use GetSystemTimeAsFileTime and convert it as needed.
For simple, non-critical timeouts:GetTickCount64 is a simple and reliable option.
Avoid the old GetTickCount function. Its 32-bit value wraps around to zero after ~49.7 days of system uptime, which is a notorious source of bugs. GetTickCount64 is the correct replacement.