i have written the code in which i want to calculate timedifference of request sent time and response receive time from device in second and microsecond. but when i executes the binary i get the response receive time earlier than request sent time which in turn returns the negative time difference.
code is given here:--
static void
this_moment(struct timeval *tv)
{
gettimeofday(tv, (void *)NULL);
}
static int
tdiff(struct timeval *after, struct timeval *before)
{
int udiff;
int sdiff;
int ret;
udiff = after->tv_usec - before->tv_usec;
sdiff = after->tv_sec - before->tv_sec;
if (udiff < 0)
{
udiff += 1000000;
sdiff -= 1;
}
return(sdiff * 1000000 + udiff);
}
int main()
{
struct timeval now1,now2;
int timedifference;
#request sent here
this_moment(&now1);
#response received here
this_moment(&now1);
timedifference=tdiff(&now2, &now1);
printf("Time elapsed for ping request is %d\n",timedifference);
}
I have used this code but i am getting -ne timedifference.
The network i used is of very high latency so getting response very quickly in 5-7 miliseconds.
Please help to to get out of this problem if some body knows about this issue.
There are some other problems, but start with this move lines around, then
this_moment(&now1);
#request sent here
#response received here
this_moment(&now2);
thank you jim for quick reply.....
i have tried all things replacing lines also ....but problem is still as it is....
actually i have added some loggings in the code and found that the time collected in now2 is older than now1 becouse of which i am getting -ve difference.....
here are loggings---
04-11-2008 02:44:49|Echo req sent to 152.168.158.58 at 1225734289sec : 675093microsec
04-11-2008 02:44:49|Echo resp received from 152.168.158.58 at 1225734289sec :674749microsec
04-11-2008 02:44:49|The ping time for 152.168.158.58 is = -344
I think gettimeofday is not returning the proper time.....
Please suggest ...
Thanks a lot.
It's your code. Here is an example, it is not really useful.
/* tmcmd.c time a command example */
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
/* time a command usage: tmcmd <command> */
int main(int argc, char **argv)
{
struct timeval first,
second,
lapsed;
double elapsed=0.;
struct timezone tzp;
gettimeofday (&first, &tzp);
system(argv[1]);
gettimeofday (&second, &tzp);
if (first.tv_usec > second.tv_usec) {
second.tv_usec += 1000000;
second.tv_sec--;
}
lapsed.tv_usec = second.tv_usec - first.tv_usec;
lapsed.tv_sec = second.tv_sec - first.tv_sec;
elapsed=lapsed.tv_sec + (1./(double)lapsed.tv_usec);
printf("\n\n%s: %f\n", argv[1], elapsed);
return 0;
}