tawheed
tawheed

Reputation: 5821

difference between two milliseconds in C

I was wondering whether there is a function in C that takes time in the following format (current date and time in seconds are in Epoch format)

a.1343323725
b.1343326383

And returns me the result as difference between the two time as hrs:mins:secs


Sorry for any confusion, to clarify my point I wrote a code that gets that gets the user's current time execute some block of code and gets the time again. And I was wondering whether the difference could be converted into hrs:mins:sec as a string literal.

#include <sys/time.h>
#include <stdio.h>
int main(void)
{
        struct timeval tv = {0};
        gettimeofday(&tv, NULL);
        printf("%ld \n", tv.tv_sec);
        //Execte some code
         gettimeofday(&tv, NULL);
        return 0;
}

Upvotes: 1

Views: 1160

Answers (2)

Dmitry Poroh
Dmitry Poroh

Reputation: 3825

 unsigned diff = b-a;
 printf("%u:%u:%u", diff/3600, (diff % 3600)/60, diff % 60);
  • diff / 3600 is hours.
  • (diff % 3600) / 60 is remainder minutes
  • (diff % 3600) % 60 equal to diff % 60 is remainder seconds

Limitation: this code don't work for diffs greater than about 136 years.

Note: It is bad idea to use gettimeofday for the performance meter. The best function to use is clock_gettime with CLOCK_MONOTONIC clock id (It is not affected by wall-clock time change). But beware CLOCK_MONOTONIC don't work in Linux kernels before 2.6. Check clock availability before use.

Upvotes: 1

Mjiig
Mjiig

Reputation: 175

First you want to get the time difference in seconds out of the timeval structures that those functions return, using something like this:

int diff = a.tv_sec-b.tv_sec;

Where a and b were the values returned by gettimeofday.

Next you want to break that down into units of hours, minutes and seconds.

int hours=diff/3600;
int minutes=(diff/60)%60;
int seconds=diff%60;

Finally we want to get that data into a string, using the snprintf function from

#include <stdio.h>
char output[10];
snprintf(output, 10, "%d:%d:%d", hours, minutes, seconds);

sprintf words exactly like printf, except the output goes into a string, not onto stdout, and snprintf is the same except it won't write more than n characters into the string, to prevent buffer overflows. Stitch those together and you've got the job done.

Upvotes: 1

Related Questions