Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print time difference in accuracy of milliseconds and nanoseconds from C in Linux?

Tags:

c

linux

time

gcc

I have this program which prints the time difference between 2 different instances, but it prints in accuracy of seconds. I want to print it in milliseconds and another in nanoseconds difference.

//Prints in accuracy of seconds

#include <stdio.h>
#include <time.h>

int main(void)
{
    time_t now, later;
    double seconds;

    time(&now);
    sleep(2);

    time(&later);
    seconds = difftime(later, now);

    printf("%.f seconds difference", seconds);
}

How can I accomplish that?

like image 683
RajSanpui Avatar asked Apr 29 '13 09:04

RajSanpui


3 Answers

Read first the time(7) man page.

Then, you can use clock_gettime(2) syscall (you may need to link -lrt to get it).

So you could try

    struct timespec tstart={0,0}, tend={0,0};
    clock_gettime(CLOCK_MONOTONIC, &tstart);
    some_long_computation();
    clock_gettime(CLOCK_MONOTONIC, &tend);
    printf("some_long_computation took about %.5f seconds\n",
           ((double)tend.tv_sec + 1.0e-9*tend.tv_nsec) - 
           ((double)tstart.tv_sec + 1.0e-9*tstart.tv_nsec));

Don't expect the hardware timers to have a nanosecond accuracy, even if they give a nanosecond resolution. And don't try to measure time durations less than several milliseconds: the hardware is not faithful enough. You may also want to use clock_getres to query the resolution of some clock.

like image 129
Basile Starynkevitch Avatar answered Oct 30 '22 11:10

Basile Starynkevitch


timespec_get from C11

This function returns up to nanoseconds, rounded to the resolution of the implementation.

Example from: http://en.cppreference.com/w/c/chrono/timespec_get :

#include <stdio.h>
#include <time.h>

int main(void)
{
    struct timespec ts;
    timespec_get(&ts, TIME_UTC);
    char buff[100];
    strftime(buff, sizeof buff, "%D %T", gmtime(&ts.tv_sec));
    printf("Current time: %s.%09ld UTC\n", buff, ts.tv_nsec);
}

Output:

Current time: 02/18/15 14:34:03.048508855 UTC

More details here: https://stackoverflow.com/a/36095407/895245


here is a simple macro to deal with it

#include <time.h>
#define CHECK_TIME(x) {\
    struct timespec start,end;\
    clock_gettime(CLOCK_REALTIME, &start);\
    x;\
    clock_gettime(CLOCK_REALTIME, &end);\
    double f = ((double)end.tv_sec*1e9 + end.tv_nsec) - ((double)start.tv_sec*1e9 + start.tv_nsec); \
    printf("time %f ms\n",f/1000000); \
    }

and here is how to use it:

CHECK_TIME(foo(a,b,c))
like image 1
yairgd Avatar answered Oct 30 '22 11:10

yairgd