拥有以下计时器的最简单方法
Simplest way to have the following timer
我目前正在尝试用一个旧的python代码用C++重写一些软件。在python版本中,我曾经有这样的计时器:
from time import time, sleep
t_start = time()
while (time()-t_start < 5) # 5 second timer
# do some stuff
sleep(0.001) #Don't slam the CPU
sleep(1)
print time()-t_start # would print something like 6.123145 notice the precision!
然而,在C++中,当我尝试从< time.h >
使用time(0)
时,我只能将精度以秒为单位作为整数,而不是浮点值。
#include <time.h>
#include <iostream>
time_t t_start = time(0)
while (time(0) - t_start < 5) // again a 5 second timer.
{
// Do some stuff
sleep(0.001) // long boost sleep method.
}
sleep(1);
std::cout << time(0)-t_start; // Prints 6 instead of 6.123145
我也尝试过< sys/time.h >
中的gettimeofday(struct, NULL)
,但每当我用boost::this_thread::sleep
睡眠程序时,它都不计算时间。。。
我希望这里有人遇到过类似的问题,并找到了解决方案。
此外,我确实需要至少毫秒精度的dt,因为在中
// Do some stuff
部分代码我可能会提前脱离while循环,我需要知道我在里面呆了多久,等等
感谢您的阅读!
gettimeofday()
已知在系统时间中出现不连续跳跃时会出现问题。
对于便携式毫秒精度,请查看chrono::high_resolution_clock()
这里有一个小片段:
chrono::high_resolution_clock::time_point ts = chrono::high_resolution_clock::now();
chrono::high_resolution_clock::time_point te = chrono::high_resolution_clock::now();
// ... do something ...
cout << "took " << chrono::duration_cast<chrono::milliseconds>(te - ts).count() << " millisecsn";
请注意,实际时钟分辨率与操作系统绑定。例如,在windows上,您通常具有15ms的精度,并且只有使用依赖于平台的时钟系统才能超越这一限制
相关文章:
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 在OSX上使用CMake将Adobe的XMP工具包构建为共享库的最简单方法是什么?
- 通过比较C++中的行在 txt 文件中搜索的最简单方法是什么?
- 将时间戳打印到流的最简单方法
- 在C++中创建文件夹选取器对话框的最简单方法是什么?
- boost::variant - 对变体应用算术的最简单方法
- 创建可以遍历 std::map 值的通用模板迭代器的最简单方法是什么?
- 在C++中将算术类型转换为 std::array 的最简单方法<uint8_t>
- C++-将ASCII字符数组中可能的数值转换为字符的最简单方法
- 从 txt 文件中读取数据的最简单方法
- 根据浮点符号对浮点进行舍入的最简单方法是什么
- 对于我扩展此程序来计算最高10x10矩阵的倒数的最简单方法是什么
- C++98 中获取并继续调用当前类不知道的类方法的最简单方法是什么?
- 编写要在 Python 中使用的并行 C/C++ 模块的最简单方法
- 开放式颜色多边形表面的最简单方法
- 确定代码中当前程序集是否为 32/64 位的最简单方法
- 将unique_ptr存储在堆上的最简单方法是什么
- 使用 C# 获取 OpenGL 版本的最简单方法
- 在自定义 C/C++ 程序中获取 PPP0 接口 Tx/Rx 字节的最简单方法是什么?
- 为depth_first_search定义颜色图的最简单方法