考虑:
#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);
耗时:0.102 秒(可变)
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);
耗时:0.105 秒(可变)
如何调整我的 Sleep() 以便程序始终在每次打印 0.100 秒时结束? (并且 doSomething(); 每 0.010 秒执行一次)。这可能吗?
到目前为止,我已经尝试计算循环的每次迭代所花费的时间,并将随后的 Sleep() 减少该数量,但无济于事。此外,如果让某事每 0.010 秒执行一次是不可能的,那么我可以持续让某事执行的最短时间是多少?
最佳答案
我(我假设还有很多其他人)在游戏中使用的技术是处理绝对时间。这会根据操作的持续时间自动调整。
例如
#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";
}
关于c++ - 在 C++ 中每 10 毫秒执行一次函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46609863/