【问题标题】:Take time in milliseconds以毫秒为单位的时间
【发布时间】:2012-04-11 15:48:16
【问题描述】:

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

【问题讨论】:

  • 您能否更清楚地说明您不喜欢usleep 的哪些方面?据我所知,它完全符合您的要求(嗯,除了是 µs 而不是 ms)。
  • 我不明白这个问题。 microtime不是你在找什么吗?
  • 问题是我不想要一个睡眠函数,而是一个“getTime in ms”函数。因为如果线程睡眠,它可能会被一些信号唤醒(例如:我按下一个键)。
  • 你可能根本不想睡觉。 “OpenGL 和睡眠”通常是一个不太顺利的组合,因为睡眠函数保证阻塞一个最短时间或更长,而不是一个精确的时间(在 POSIX 下甚至没有,在信号!)。也就是说,普通的 gettimeofday 函数在毫秒分辨率(实际上是微)下工作没问题。

标签: c++


【解决方案1】:

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

#include <boost/thread.hpp>

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

正如您在代码中看到的,这个简单的示例休眠了 2000 毫秒。

编辑:

好的,我以为我理解了这个问题,但后来我阅读了 cmets,现在我不再那么确定了。

也许您想获取自某个点/事件以来经过了多少毫秒?如果是这种情况,那么您可以执行以下操作:

#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】:

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

    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
    }
    

    【讨论】:

    • 我需要一个类似 time() 的函数,但会得到 ms。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2019-09-11
    • 2011-03-09
    • 2012-04-28
    • 1970-01-01
    相关资源
    最近更新 更多