linux启动时间和停止计时器不起作用?

时间:2014-02-23 08:11:58

标签: c linux timer timertask

#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

#include <netinet/in.h>
#include <arpa/inet.h>

typedef unsigned int uint32;

#define million 1000000L

long duration2ms, duration10ms, duration100ms;
double Task2ms_Raster, Task10ms_Raster, Task100ms_Raster;
timer_t firstTimerID, secondTimerID, thirdTimerID;

void TASK1(Task2ms_Raster) {
    struct timespec start, stop;
    int a, b, c;
    uint32 StartTime, StopTime;
    a=100, b=2;

    if((StartTime = clock_gettime(CLOCK_REALTIME, &start)) == -1) {
        perror("clock gettime");
    }
    printf("start time is= %ld\n", StartTime);
    //I am performing some computation like 
    a = a + 100;
    b = a + 120;
    a = a + b;
    b = a;
    c = b;
      if((StopTime = clock_gettime( CLOCK_REALTIME, &stop)) == -1) {
        perror("clock gettime");
    }

 printf("stop time is= %ld\n", StopTime);

    duration2ms = (stop.tv_sec - start.tv_sec) +
                  (double)(stop.tv_nsec - start.tv_nsec) /
                  (double)million;
    printf("time difference is= %ld\n", duration2ms);
}

我创建了计时器并且每2ms,10ms和100ms调用任务。以上是2ms任务的代码。我想计算在任务中执行某些计算的开始时间和停止时间,最后想知道它之间的时间差。当我运行我的应用程序时,它只显示时差(即duration2ms)。它不打印StartTime和StopTime。有人可以帮助我。

2 个答案:

答案 0 :(得分:2)

如果您阅读clock_gettime的手册页,您会看到

  

clock_gettime()返回0表示成功,或-1表示失败。

因此,您只打印返回代码。要打印开始时间和停止时间,您需要打印变量startstop的内容。例如:

   printf("Start time: %d.%09d\n", start.tv_sec, start.tv_nsec);

答案 1 :(得分:0)

你需要的是什么

uint64_t u64StartTime = (start.tv_sec * 100000000) + start.tv_nsec;