Reputation: 11
Consider:
#include <time.h>
#include <windows.h>
clock_t tStart = clock();
for (int i = 0; i < 10; i++) {
Sleep(10);
}
printf("Time taken: %.3fs\n", (double)(clock() - tStart) / CLOCKS_PER_SEC);
Time taken: 0.102 s (varied)
clock_t tStart = clock();
for (int i = 0; i < 10; i++) {
doSomething();
Sleep(10);
}
printf("Time taken: %.3fs\n", (double)(clock() - tStart) / CLOCKS_PER_SEC);
Time taken: 0.105 s (varied)
How can I adjust my Sleep() so that the program consistently ends on printing 0.100 s each time? (and that doSomething(); executes exactly every 0.010s). Is that even possible?
So far I have tried to calculate the time each iteration of the loop takes and decrease the following Sleep() by that amount, but to no avail. Additionally, if making something execute every 0.010 s is not possible, what is the minimum time I can consistently make something execute at?
Upvotes: 0
Views: 4001
Reputation: 69864
The technique that I (and I assume many others) use in games is to deal in absolute time. This automatically adjusts for the duration of the action.
e.g.
#include <chrono>
#include <thread>
#include <iostream>
using namespace std::literals;
using clock_type = std::chrono::high_resolution_clock;
void doSomething() {}
int main()
{
auto when_started = clock_type::now();
auto target_time = when_started + 10ms;
for (int i = 0; i < 10; i++) {
doSomething();
std::this_thread::sleep_until(target_time);
target_time += 10ms;
}
auto now = clock_type::now();
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(now - when_started).count() << "ms\n";
}
Upvotes: 8