我已经从另一个问题中发现,Windows/MingW没有提供nanosleep()和setitimer()替代过时的usleep()。但是我的目标是修复cppcheck给我的所有警告,包括us休眠()样式的警告。
那么,在不使用cygwin或安装大量新的依赖项/库的情况下,是否有办法避免在Windows上使用us休眠()呢?谢谢。
发布于 2011-04-27 09:26:59
usleep()
的工作时间为微秒。在获取微秒的窗口中,您应该使用QueryPerformanceCounter() winapi函数。这里,您可以找到如何使用它来获得这个过程。
发布于 2013-06-24 19:30:47
我使用了以下代码(最初来自这里):
#include <windows.h>
void usleep(__int64 usec)
{
HANDLE timer;
LARGE_INTEGER ft;
ft.QuadPart = -(10*usec); // Convert to 100 nanosecond interval, negative value indicates relative time
timer = CreateWaitableTimer(NULL, TRUE, NULL);
SetWaitableTimer(timer, &ft, 0, NULL, NULL, 0);
WaitForSingleObject(timer, INFINITE);
CloseHandle(timer);
}
请注意,SetWaitableTimer()
使用"100纳秒间隔.正值表示绝对时间.负值表示相对时间“。“实际计时器的准确性取决于硬件的能力。”
如果您有一个C++11编译器,那么您可以使用这可移植版本:
#include <chrono>
#include <thread>
...
std::this_thread::sleep_for(std::chrono::microseconds(usec));
霍华德·辛纳特( Hinnant )设计了一个令人惊叹的<chrono>
图书馆( 他的答案如下理应得到更多的爱)。
如果您没有C++11,但是有boost,那么您可以使用这:
#include <boost/thread/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
...
boost::this_thread::sleep(boost::posix_time::microseconds(usec));
发布于 2015-08-31 20:09:48
旧问题的新答案:
新答案的基本原理:工具/开放源码软件已经更新,比最初提出问题时有更好的选择。
C++11 <chrono>
和<thread>
std标头已经在VS工具集中使用了好几年。使用这些标头,最好在C++11中编码如下:
std::this_thread::sleep_for(std::chrono::microseconds(123));
我只使用微秒作为一个例子。您可以使用任何合适的持续时间:
std::this_thread::sleep_for(std::chrono::minutes(2));
使用C++14和一些使用指令的代码,可以编写得更简洁一些:
using namespace std::literals;
std::this_thread::sleep_for(2min);
或者:
std::this_thread::sleep_for(123us);
这肯定适用于VS-2013 (模块化的时间文字)。我不确定VS的早期版本。
https://stackoverflow.com/questions/5801813
复制相似问题