2012-04-11 212 views
4

我在unistd.h中找到了usleep函数,我认为在每个动作之前等待一段时间是有用的。但是我发现线程只是在睡眠状态,如果它没有收到任何信号。例如,如果我按下一个按钮(我正在使用OpenGL,但问题是关于time.h和unistd.h的更具体的),线程会被唤醒,而我没有得到我想要的。 在time.h中有睡眠函数接受一个整数,但整数太多(我想等待0.3秒),所以我使用usleep。 我问是否有一个函数需要毫秒的时间(从任何GNU或任何库)。 它应该像time()一样工作,但返回毫秒而不是秒。是否可能?花费时间以毫秒为单位

+0

你能清楚哪些是你不喜欢'usleep'更清楚了吗?尽我所能地告诉它它确实是你想要的(当然,除了是μs而不是ms)。 – 2012-04-11 15:52:32

+0

我不明白这个问题。不是'microtime'你在找什么? – nothrow 2012-04-11 15:52:41

+0

问题是我不想要一个睡眠函数,而是一个“getTime in ms”函数。因为如果线程休眠,它可能会被一些信号唤醒(例如:我按下一个键)。 – 2012-04-11 15:57:07

回答

4

这是一个跨平台的功能,我使用:

unsigned Util::getTickCount() 
{ 
#ifdef WINDOWS 
    return GetTickCount(); 
#else 
    struct timeval tv; 
    gettimeofday(&tv, 0); 
    return unsigned((tv.tv_sec * 1000) + (tv.tv_usec/1000)); 
#endif 
} 
+0

我需要一个像time()这样的函数,但是会得到ms。 – 2012-04-11 15:58:18

+0

@RamyAlZuhouri:好的,我编辑了我的答案。 – trojanfoe 2012-04-11 17:02:04

7

如果你有提升,你可以这样来做:

#include <boost/thread.hpp> 

int main() 
{ 
    boost::this_thread::sleep(boost::posix_time::millisec(2000)); 
    return 0; 
} 

这个简单的例子,你可以在代码中看到,睡2000ms。

编辑:

好吧,我想我明白这个问题,但后来我读的意见,现在我不那么肯定了。

也许你想知道自从某个点/事件以来经过了多少毫秒?如果是这样的话,那么你可以这样做:

#include <boost/chrono.hpp> 
#include <boost/thread.hpp> 
#include <iostream> 


int main() 
{ 
    boost::chrono::high_resolution_clock::time_point start = boost::chrono::high_resolution_clock::now(); 
    boost::this_thread::sleep(boost::posix_time::millisec(2000)); 
    boost::chrono::milliseconds ms = boost::chrono::duration_cast<boost::chrono::milliseconds> (boost::chrono::high_resolution_clock::now() - start); 
    std::cout << "2000ms sleep took " << ms.count() << "ms " << "\n"; 
    return 0; 
} 

(请原谅排长)

+2

“请原谅长排”......哦可爱的助推库:) – Marlon 2012-04-11 16:40:40

+0

@Marlon你是那么对! :-) – mantler 2012-04-11 16:42:58

相关问题