在 c++ 中获取以毫秒为单位的时差
Get time difference in milliseconds in c++
我正在尝试获取两个时间戳之间的时间差。线程在两个时间戳之间休眠。但是当我得到差异时,它不会给我线程休眠的时间。我的代码如下。
#include <iostream>
#include <locale>
#include <sys/time.h>
#include <cstdlib>
#include <unistd.h>
using namespace std;
int timeInMilli();
int main()
{
timeval t;
timeval t2;
gettimeofday(&t, NULL);
gettimeofday(&t2, NULL);
std::string buf(20, ' ');
std::strftime(&buf[0], buf.size(), "%H:%M:%S:", localtime(&t.tv_sec));
std::string hr = buf.substr(0, 2);
std::string min = buf.substr(3, 2);
std::string sec = buf.substr(6, 2);
/*std::cout << hr << 'n';
std::cout << min << 'n';
std::cout << std::atoi(sec.c_str()) << 'n';*/
int a = timeInMilli();
usleep(10);
int b = timeInMilli();
cout << b-a << endl;
}
int timeInMilli()
{
timeval t;
gettimeofday(&t, NULL);
string buf(20, ' ');
strftime(&buf[0], buf.size(), "%H:%M:%S:", localtime(&t.tv_sec));
string str_hr = buf.substr(0, 2);
string str_min = buf.substr(3, 2);
string str_sec = buf.substr(6, 2);
int hr = atoi(str_hr.c_str());
int min = atoi(str_min.c_str());
int sec = atoi(str_sec.c_str());
int milli = t.tv_usec/1000;
/*cout << hr << endl;
cout << min << endl;
cout << sec << endl;
cout << milli << endl;*/
int timeInMilli = (((hr * 60) + min) * 60 + sec) * 1000 + milli;
return timeInMilli;
}
usleep(10);
意味着您暂停 10 微秒而不是 10 毫秒,因为 Usleep 以微秒为单位工作。 尝试使用
usleep(10000);
相关文章:
- 以天C++为单位的两个时间戳之间的差异
- 如何以毫秒为单位获取开始时间和 now() 之间的毫秒差异(以 C++为单位?
- 从原始字节解码协议缓冲区(以 C++为单位)
- 如何在 c++ 中确定一条指令(以字节为单位)在哪里结束,另一条指令从哪里开始?
- 编写以 C++ 为单位返回值的函数
- 以C++为单位进行运行长度编码
- 如何找到两个日期之间的时间差异(以秒和纳秒为单位)?
- arr[n] 是否以 C++ 为单位打印数组的长度?
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 以 C++ 为单位具有输出限制的排列
- 以 GDB 为单位指定浮点精度
- 整数数据如何以位为单位存储在内存中?不是右对齐吗?
- 如何在没有硬编码的情况下以C++为单位获取类数组的长度?
- 指针引用的生存期(以 C++为单位)
- 以字符为单位设置控制台大小
- 获取嵌套 stl 容器的大小(以字节为单位)
- 有没有一种 STL 方法可以找到字符串的所有排列,给出一个以 C++ 为单位的大小?
- 如何找到纪元时间戳和 std::chrono::system_clock::now 之间的时差(以毫秒为单位)
- 如何在跨平台 c++ 32 位系统中获取以毫秒为单位的时差
- 在 c++ 中获取以毫秒为单位的时差