I'am trying to make a time meter. My OS is Windows.
Here is a small piece of code that gives a strange result.
If a thread sleeps for 1ms and does this 5000 times, then I would expect it to take roughly 5 seconds.
But I get as a result that test_time = 12.8095
Do not understand why?
How can I fix the code so that I get a time meter that can measure durations of about 1 millisecond?
std::atomic_bool work = true;
size_t cnt{};
std::chrono::duration<double> operation_time;
double test_time;
auto start_time_ = std::chrono::high_resolution_clock::now();
std::thread counter_ = std::thread([&work, &cnt]() {
while (work) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
cnt++;
if (cnt >= 5000)
work = false;
}
});
if (counter_.joinable())
counter_.join();
operation_time = std::chrono::duration<double>(std::chrono::high_resolution_clock::now() - start_time_);
test_time = operation_time.count();
std::cout << "test_time = " << test_time << std::endl;