【问题标题】:how to solve this linux Timer error如何解决这个 linux Timer 错误
【发布时间】:2014-02-25 14:02:30
【问题描述】:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>

#define BILLION  1000000000L;

int main( int argc, char** argv )
  {
    struct timespec start, stop;
    double accum;
    uint32 StartTime, StopTime;



    if( StartTime = clock_gettime( CLOCK_REALTIME, &start) == -1 ) {
      perror( "clock gettime" );
      return EXIT_FAILURE;
    }

StartTime = start.tv_sec + 0.0000000001 * start.tv_nsec;
    system( argv[1] ); // or it could be any calculation

    if( StopTime = clock_gettime( CLOCK_REALTIME, &stop) == -1 ) {
      perror( "clock gettime" );
      return EXIT_FAILURE;
    }

StopTime = stop.tv_sec + 0.0000000001 * stop.tv_nsec;

 accum = StopTime - StartTime;
    printf( "%lf\n", accum );
    return EXIT_SUCCESS;
  }

这个程序计算需要的时间 执行指定为其第一个参数的程序。 时间以秒为单位打印,标准输出。 我正在计算开始时间和停止时间以执行一些计算。我能够获得计算的开始时间和停止时间,但无法找到开始时间和停止时间之间的差异,即累积。有人可以帮我吗?

【问题讨论】:

  • 声明StartTimeStopTimedouble如果你不想分配这种表达式start.tv_sec + 0.0000000001 * start.tv_nsec;
  • 如果是uint32怎么修改??

标签: c linux timer clock


【解决方案1】:

删除StartTimeStopTime。声明这个函数:

double to_double(struct timespec t) {
    return t.tv_sec + 0.0000000001 * t.tv_nsec;
}

这样你就可以得到你的 deltatime 了:

accum = to_double(stop) - to_double(start);

【讨论】:

  • 我想计算 Starttime 和 Stoptime 以及两者之间的差异。
  • StartTime = to_double(start), StopTime = to_double(stop), accum 是你的区别。
【解决方案2】:

问题在于StartTimeStopTime 都被定义为整数类型。您的计算结果不是整数,但由于表达式的左侧是整数,因此结果被截断为整数部分。从本质上讲,您丢失了tv_nsec 字段提供的详细信息。

按照 cmets 中的建议,将 StartTimeStopTime 声明为双精度以解决此问题。

改变

uint32 StartTime, StopTime;

double StartTime, StopTime;

【讨论】:

    猜你喜欢
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    相关资源
    最近更新 更多