C Unix Millisecond Timer returning difference of 0

2019-08-04 01:01发布

Can anyone explain why I always get a time of 0 from the code below? I just want a millisecond timer to calculate the delay between sending and receiving data from a socket but no matter what I try, I always get a result of 0...I even tried microseconds just in case my system was executing it in less than 1ms.

    printf("#: ");

    bzero(buffer,256);
    fgets(buffer,255,stdin);

    struct timeval start, end;

    unsigned long mtime, seconds, useconds;    

    gettimeofday(&start, NULL);  

    n = write(clientSocket,buffer,strlen(buffer));

    if (n < 0)
    {
        error("Error: Unable to write to socket!\n");
    }

    bzero(buffer,256);
    n = read(clientSocket,buffer,255);

    gettimeofday(&end, NULL);

    seconds  = end.tv_sec  - start.tv_sec;
    useconds = end.tv_usec - start.tv_usec;

    mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;      

    if (n < 0) 
    {
        error("Error: Unable to read from socket!\n");
    }

    printf("%s\n",buffer);
    printf("Delay: %lu microseconds\n", useconds);

标签: c unix timer
2条回答
霸刀☆藐视天下
2楼-- · 2019-08-04 01:14

Assuming your result is in mtime: mtime is integer and you calculate elapsed time with float numbers so if

((seconds) * 1000 + useconds/1000.0) + 0.5

evaluates to < 1.0 casting to integer will cut it to 0

simply change mtime type to float, or if you can keep micro seconds use

((seconds) * 1000000 + useconds) + 500
查看更多
霸刀☆藐视天下
3楼-- · 2019-08-04 01:36

useconds = end.tv_usec - start.tv_usec; is questionable with unsigned long useconds; since the result may well be negative.

Suggestion:

unsigned long end_us,start_us,elapsed_us;

   .
   .
   .

end_us     = end.tv_sec   * 1000000  +  end.tv_usec;
start_us   = start.tv_sec * 1000000  +  start.tv_usec;

elapsed_us = end_us - start_us;

printf("elapsed microseconds: %lu\n", elapsed_us);

And:

mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;  

is to be looked at too: This attempts to convert to milliseconds. It is not clear why you add 0.5.

Suggestion:

elapsed_ms = elapsed_us / 1000;

But defining elapsed_ms as an integer would unnecessarily cut the result to full milliseconds. A float may be considered here.

查看更多
登录 后发表回答