Home > OS >  How to define C API to get current time count in nanosecond?
How to define C API to get current time count in nanosecond?

Time:02-10

I need to define C API ex. GetTimerCountInNS(void) to get current TimerCount in Nanosecond, so using this API call I can calculate total execution time of some work done in nanosecond. Can someone suggest me what is wrong with my GetTimerCountInNS function as when I am calculating total execution time it shows incorrect execution time however for MilliSecond it shows correct one.

I already checked other query related to same one but I could not found exact answer.As I dont want to write all equation into main code when calculating time in nanosecond.

I need to use custom API to get count in Nanosecond and by getting different of start and stop time count I need to get total execution time.

How to get current timestamp in nanoseconds in linux using c

Calculating Function time in nanoseconds in C code

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>

#define BILLION  1000000000L;

// This API provides incorrect time in NS duration
uint64_t GetTimerCountInNS(void)
{
   struct timespec currenttime;
   clock_gettime( CLOCK_REALTIME, &currenttime);

   //I am not sure here how to calculate count in NS
   return currenttime.tv_nsec;
}

// This API provides correct time in MS duration
uint64_t GetTimerCountInMS(void)
{
   struct timespec currenttime;
   clock_gettime( CLOCK_REALTIME, &currenttime);
   return (1000 * currenttime.tv_sec)   ((double)currenttime.tv_nsec / 1e6);
}

int main( int argc, char** argv )
  {
    struct timespec start, stop;
    uint64_t start_ns,end_ns;
    uint64_t start_ms,end_ms;
    

    clock_gettime( CLOCK_REALTIME, &start);
    start_ms = GetTimerCountInMS();
    start_ns  = GetTimerCountInNS();

    int  f = 0;
    sleep(3);
    clock_gettime( CLOCK_REALTIME, &stop);

    end_ms = GetTimerCountInMS();
    end_ns  = GetTimerCountInNS();

    double total_time_sec = ( stop.tv_sec - start.tv_sec )   (double)( stop.tv_nsec - start.tv_nsec ) / (double)BILLION;
    printf( "time in sec \t: %lf\n", total_time_sec );
    printf( "time in ms \t: %ld\n", (end_ms - start_ms) );
    printf( "time in ns \t: %ld\n", (end_ns - start_ns) );

    return EXIT_SUCCESS;
  }
Output:
time in sec     : 3.000078
time in ms      : 3000
time in ns      : 76463   // This shows wrong time

CodePudding user response:

A fix:

uint64_t GetTimerCountInNS(void) {
   struct timespec currenttime;
   clock_gettime(CLOCK_REALTIME, &currenttime);
   return UINT64_C(1000000000) * currenttime.tv_sec   currenttime.tv_nsec;
}

In the return, a uint64_t constant is used to promote all other operands of the binary arithmetic operators to uint64_t, in addition to converting seconds to nanoseconds.

  • Related