-2
double GetTimeStamp()
{
    struct timespec start;

    if((clock_gettime( CLOCK_MONOTONIC, &start)) == -1 )
    {
        perror("clock gettime\n");
    }

    return start.tv_sec + start.tv_nsec * 1e-9;   //seconds
}

MAIN.c:

uint64_t Receive;
uint32 receiveTime;
int main()
{
    rc=recvfrom(sock, buf, 256, 0, (struct sockaddr*) &client, &len);
    Receive = GetTimeStamp();
    receiveTime = (uint32) (Receive / 1000000);    // I am converting to microseconds
    printf("Receive time: %lu\n", receiveTime);
}

I am taking a timestamp and reading that time from another program as shown above. But I am not getting any value if I do as above. Why is it not displaying any value in main?

Mat
  • 202,337
  • 40
  • 393
  • 406
  • 2
    you do cast to int, that does cut off everything after the decimal point. so if you have 1 second -> `(int)(1/ 100000) = 0` – Theolodis May 22 '14 at 08:29
  • then what is the solution for that ?? double will be a very big value. – user3635707 May 22 '14 at 08:30
  • Oh, I just noticed that your conversion is bad anyway. nano_seconds to seconds is `nano_seconds / 1e-9;` and seconds to microseconds is: `seconds * 1e6` – Theolodis May 22 '14 at 08:33
  • And if you do really want to print what you have actually: `double receiveTime = 1.000000555; printf("Receive time: %0.8f\n", receiveTime)` – Theolodis May 22 '14 at 08:35
  • 1) Although I doubt this is your problem, `printf("Receive time: %lu\n", receiveTime);` is UB. Should be `printf("Receive time: %" PRIu32 "\n", receiveTime);`. 2) Sure code is returning from `recvfrom()`? – chux - Reinstate Monica May 22 '14 at 14:11

1 Answers1

1

By

I am not getting any value if I do as above. Why is it not displaying any value in main?

do you mean that 0 is displayed, or that nothing at all is displayed?

Assuming the former, CLOCK_MONOTONIC defaults to starting at boot time (Starting point for CLOCK_MONOTONIC), so it measures the up time of the system. Now your GetTimeStamp code returns the number of seconds since boot time as a double, and you then divide that by 1,000,000 with the incorrect comment "I am converting to microsecond". In fact, you are dividing the number of seconds since boot by 1 million, so this is likely to return 0 unless your systems has been up for over 1,000,000 seconds. That would be over 11 days. So if your system has been up for less time than that, you would expect to keep seeing 0 as the output.

Assuming the latter, your recvfrom call is probably blocking. You could verify this by commenting it out and seeing that the code then at least produces output.

Community
  • 1
  • 1
mc110
  • 2,825
  • 5
  • 20
  • 21