如何定义 C API 以纳秒为单位获取当前时间计数?

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

我需要定义 C API ex。 GetTimerCountInNS(void) 以纳秒为单位获取当前 TimerCount,因此使用此 API 调用我可以计算以纳秒为单位完成的某些工作的总执行时间。有人可以告诉我我的 GetTimerCountInNS 函数有什么问题吗,因为当我计算总执行时间时它显示不正确的执行时间但是对于 MilliSecond 它显示正确的执行时间。

我已经检查了与同一查询相关的其他查询,但我找不到确切的 answer.As 我不想在计算纳秒时间时将所有方程写入主代码。

我需要使用自定义 API 来获取以纳秒为单位的计数,通过获取不同的开始和停止时间计数,我需要获取总执行时间。

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

修复:

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

在return中,除了将秒转换为纳秒外,还使用uint64_t常量将二进制算术运算符的所有其他操作数提升为uint64_t