在for循环中,c++中的时间(以毫秒为单位)始终相同
Time in miliseconds in c++ in a for loop always same
我有一个类似于的for循环
ofstream myfile;
myfile.open ("clnt.txt",std::ofstream::out | std::ofstream::app);
struct timeval tv;
gettimeofday(&tv, NULL);
for(int i=0;i<100;i++)
{
double time_in_mill1 =
(tv.tv_sec) * 1000 + (tv.tv_usec) / 1000 ;
cout<<time_in_mill1<<endl;
int n1=sprintf (den, "%lf", time_in_mill1);
printf ("[%s] is a string %d chars longn",den,n1);
myfile << den;
}
并且在clnt.txt文件中,所有值都是"-2090430839.000000",并且在屏幕上为所有time_in_mill1值写入"-2.09043e+09"。我预计至少有两个值是不同的。我做错了什么?
您需要将gettimeofday移动到循环中,并更正划分
for(int i=0;i<100;i++)
{
gettimeofday(&tv, NULL);
double time_in_mill1 =
(tv.tv_sec) * 1000 + (tv.tv_usec) / 1000.0 ;
...
}
我刚刚忘记更新gettimeofday()。现在每个值都不同。谢谢你的回答。
ofstream myfile;
myfile.open ("clnt.txt",std::ofstream::out | std::ofstream::app);
struct timeval tv;
gettimeofday(&tv, NULL);
for(int i=0;i<100;i++)
{
gettimeofday(&tv, NULL);
double time_in_mill1 =
(tv.tv_sec) * 1000 + (tv.tv_usec) / 1000.0 ;
cout<<time_in_mill1<<endl;
int n1=sprintf (den, "%lf", time_in_mill1);
printf ("[%s] is a string %d chars longn",den,n1);
myfile << den;
}
相关文章:
- 以天C++为单位的两个时间戳之间的差异
- 如何以毫秒为单位获取开始时间和 now() 之间的毫秒差异(以 C++为单位?
- 从原始字节解码协议缓冲区(以 C++为单位)
- 如何在 c++ 中确定一条指令(以字节为单位)在哪里结束,另一条指令从哪里开始?
- 编写以 C++ 为单位返回值的函数
- 以C++为单位进行运行长度编码
- 如何找到两个日期之间的时间差异(以秒和纳秒为单位)?
- arr[n] 是否以 C++ 为单位打印数组的长度?
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 以 C++ 为单位具有输出限制的排列
- 以 GDB 为单位指定浮点精度
- 整数数据如何以位为单位存储在内存中?不是右对齐吗?
- 如何在没有硬编码的情况下以C++为单位获取类数组的长度?
- 指针引用的生存期(以 C++为单位)
- 以字符为单位设置控制台大小
- 获取嵌套 stl 容器的大小(以字节为单位)
- 为什么我不能将 size() 函数编写为 while 循环中的条件?
- 有没有一种 STL 方法可以找到字符串的所有排列,给出一个以 C++ 为单位的大小?
- while 循环中变量的作用域(以 C++ 为单位)
- 在for循环中,c++中的时间(以毫秒为单位)始终相同