Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/145.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 以毫秒为单位的时间,单位为c++;在for循环中总是相同的_C++_For Loop_Time - Fatal编程技术网

C++ 以毫秒为单位的时间,单位为c++;在for循环中总是相同的

C++ 以毫秒为单位的时间,单位为c++;在for循环中总是相同的,c++,for-loop,time,C++,For Loop,Time,我有一个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_

我有一个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 long\n",den,n1);
                myfile << den;
        }
流myfile的
;
myfile.open(“clnt.txt”,std::ofstream::out | std::ofstream::app);
结构时间值电视;
gettimeofday(&tv,NULL);

对于(inti=0;i您需要将gettimeofday移动到循环中并更正除法

for(int i=0;i<100;i++)
{
    gettimeofday(&tv, NULL);
    double time_in_mill1 = 
      (tv.tv_sec) * 1000 + (tv.tv_usec) / 1000.0 ; 
    ...
 }

for(int i=0;i我刚刚忘记更新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 long\n",den,n1);
              myfile << den;
     }
流myfile的
;
myfile.open(“clnt.txt”,std::ofstream::out | std::ofstream::app);
结构时间值电视;
gettimeofday(&tv,NULL);

对于(int i=0;i使用整数除法会丢失微秒分辨率。因此,如果循环在一毫秒内完成,所有记录的时间都可能相同。或者如果系统上的
gettimeofday
不是很精确。我建议改为使用
clock\u gettime
。谢谢。我正在尝试将数据包从客户端发送到服务器,然后重试。)我需要测量发送数据包之间的时差,我的意思是延迟,如果我使用clock_gettime,它对测量客户端和服务器之间的时差有影响吗?我已经更改了我的代码,现在每个值都是“-2089269230.650000”。我认为for循环在1毫秒内完成。@user3246402最有可能是这样。您可以将Sleep函数插入到循环t中o减慢其执行速度。或者只编写类似于for的内容(inti=0;i<1000000;i++)