LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   how to calculate time difference in milliseconds in C/C++ (https://www.linuxquestions.org/questions/programming-9/how-to-calculate-time-difference-in-milliseconds-in-c-c-711096/)

Biddle 03-17-2009 01:17 PM

Well I suppose the question is:
How do you suppose we represent a negative number in an unsigned int?
In reflection both codes return a value which indicates if the value is positive or negative, which I failed to notice in your code sample.
I stand corrected.

paulsm4 03-17-2009 01:33 PM

Hi, waqasdaar -

Now that you've got these cool routines (and they *are* cool!) ... please be sure to take the results with a pound of salt (or better, to quote Andrew Tanenbaum, with a "metric ton of salt").

Results are seldom accurate to-the-millisecond, much less to the microsecond. At the very least, you'll definitely want to run multiple tests, and average your results...

wje_lq 03-17-2009 01:45 PM

Quote:

Originally Posted by paulsm4 (Post 3478484)
Now that you've got these cool routines (and they *are* cool!) ... please be sure to take the results with a pound of salt (or better, to quote Andrew Tanenbaum, with a "metric ton of salt").

Your, um, timing, sir, is impeccable.

ta0kira 03-17-2009 02:24 PM

I don't understand why the other functions posted are so complicated. It can be done in a single long line.
Code:

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <sys/timex.h>


static int difference_micro(struct ntptimeval *bBefore,
struct ntptimeval *aAfter)

{
        return (signed long long) aAfter->time.tv_sec * 1000000ll +
              (signed long long) aAfter->time.tv_usec -
              (signed long long) bBefore->time.tv_sec * 1000000ll -
              (signed long long) bBefore->time.tv_usec;

}

int main()
{
        srand(time(NULL));
        struct ntptimeval start, elapsed;

        struct timespec timeout = { rand() % 2, rand() % 1000000000 };

        ntp_gettime(&start);
        nanosleep(&timeout, NULL);
        ntp_gettime(&elapsed);

        fprintf(stdout, "{ %u, %.9u } -> %ims\n", timeout.tv_sec, timeout.tv_nsec,
          difference_micro(&start, &elapsed) / 1000);
}

Kevin Barry

wje_lq 03-17-2009 04:02 PM

Quote:

Originally Posted by ta0kira (Post 3478529)
I don't understand why the other functions posted are so complicated. It can be done in a single long line.

You're right, it can. But the reason the other functions are that way is not because waqasdaar needed the extra complication (he didn't), but because of the history of the thread. jiml8 posted something that worked for him, which returned the difference as a struct timeval. I changed it somewhat so it returned both a struct timeval and a long long.

The code kinda changed incrementally. Or, as one of my past cow-orkers was known to say, "excrementally".


All times are GMT -5. The time now is 09:13 PM.