【问题标题】:How to define C API to get current time count in nanosecond?如何定义 C API 以纳秒为单位获取当前时间?
【发布时间】:2022-02-09 03:48:14
【问题描述】:

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

我已经检查了与同一查询相关的其他查询,但我找不到确切的答案。因为我不想在以纳秒为单位计算时间时将所有方程式写入主代码。

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

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

【问题讨论】:

    标签: c linux time


    【解决方案1】:

    修复:

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

    在返回中,uint64_t 常量用于将二元算术运算符的所有其他操作数提升为 uint64_t,除了将秒转换为纳秒。

    【讨论】:

      猜你喜欢
      • 2019-02-04
      • 1970-01-01
      • 1970-01-01
      • 2015-07-12
      • 2017-11-29
      • 2016-07-04
      • 2017-04-25
      • 1970-01-01
      相关资源
      最近更新 更多