以下程序的格式说明符是什么?

时间:2014-03-06 12:42:52

标签: c++ c linux timer format-specifiers

void TASK(Task100ms_Raster)
{
    int a,b,c;
    struct timespec start, stop;
    uint32 StartTime, StopTime;
    uint32 duration100ms;

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

    StartTime =start.tv_sec + 0.0000001 * start.tv_nsec;
    printf("start time is %lu", StartTime);

    printf("value is %d",c);
    printf("ETAS1\n");
    if( (StopTime = clock_gettime( CLOCK_REALTIME, &stop)) == -1 )
    {
      perror( "clock gettime" );
    }
    StopTime =  stop.tv_sec + 0.0000001 * stop.tv_nsec;
    printf("stop time is %lu", StopTime);

    duration100ms = StopTime -StartTime;
    printf( "time difference is= %lu\n", duration100ms );
}

我创建了计时器,它计算开始时间,停止时间和时间之间的差异。我对开始时间,停止时间和suration100ms的格式说明符感到困惑。但是struct timespec开始,停止;是http://www.qnx.com/developers/docs/6.3.0SP3/neutrino/lib_ref/t/timespec.html类型然后可以是正确的格式说明符来获得结果。一些人指导我。

1 个答案:

答案 0 :(得分:0)

您正在进行浮点计算以计算秒数,但将结果存储为整数:

StartTime = start.tv_sec + 0.0000001 * start.tv_nsec;

这会将结果截断为整数。您应该将StartTime变为double,然后将其打印出来:

double StartTime = start.tv_sec + 1e-9 * start.tv_nsec;

printf("start time is %f\n", StartTime);

我认为精确度更好,在计算差异时转换为float:

double duration = StopTime.tv_sec - StartTime.tv_sec +
                  1E-9 * (StopTime.tv_nsec - StartTime.tv_nsec);

如果必须将持续时间设为整数,单位为100 ms,则可以执行以下操作:

duration = 10000 * (StopTime.tv_sec - StartTime.tv_sec) + 
           (StopTime.tv_nsec - StartTime.tv_nsec) / 100000000;