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);
Assuming your result is in mtime: mtime is integer and you calculate elapsed time with float numbers so if
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
useconds = end.tv_usec - start.tv_usec;
is questionable withunsigned long useconds;
since the result may well be negative.Suggestion:
And:
is to be looked at too: This attempts to convert to milliseconds. It is not clear why you add 0.5.
Suggestion:
But defining
elapsed_ms
as an integer would unnecessarily cut the result to full milliseconds. A float may be considered here.