在C++中实现延时计时器可以使用以下几种方法:
std::this_thread::sleep_for()
函数进行延时:#include <iostream>
#include <chrono>
#include <thread>
int main() {
std::cout << "Start" << std::endl;
std::chrono::seconds delay(5);
std::this_thread::sleep_for(delay);
std::cout << "End" << std::endl;
return 0;
}
std::chrono::steady_clock
实现计时器:#include <iostream>
#include <chrono>
int main() {
std::cout << "Start" << std::endl;
auto start = std::chrono::steady_clock::now();
std::chrono::seconds delay(5);
while (std::chrono::steady_clock::now() - start < delay) {
// do nothing, just wait
}
std::cout << "End" << std::endl;
return 0;
}
std::this_thread::sleep_until()
函数进行延时:#include <iostream>
#include <chrono>
#include <thread>
int main() {
std::cout << "Start" << std::endl;
auto start = std::chrono::system_clock::now();
std::chrono::seconds delay(5);
std::this_thread::sleep_until(start + delay);
std::cout << "End" << std::endl;
return 0;
}
这些方法都可以实现延时计时器的功能,具体选择哪种方法取决于实际需求和场景。