My c-function using difftime returns 65535 sometimes

后端 未结 2 1837
隐瞒了意图╮
隐瞒了意图╮ 2021-01-26 00:05

I have a function that uses difftime to detect the time in seconds since the communication heartbeat has stopped. This function could run as fast as every 50 milliseconds. The

2条回答
  •  没有蜡笔的小新
    2021-01-26 01:08

    Before querying time, read the time(7) man page (and read it again).

    The, I suggest using clock_gettime(2) with e.g. CLOCK_MONOTONIC or CLOCK_REALTIME, and preferably use double for time calculations (since a struct timespec is generally larger than any integral type).

    Don't use uint16_t for such time calculations.

    Try using

    inline double double_gettime (clockid_t cid) {
      struct timespec ts = {0,0};
      clock_gettime(cid, &ts);
      return (double)ts.tv_sec + 1.0e-9*ts.tv_nsec;
    }
    

    You might want to make that function fancier, by testing if clock_gettime is failing and giving NAN when it fails! This is left as an exercise to the reader. You could also, for CLOCK_REALTIME etc, measure the difference between some time at start of process and the current time (i.e. compute a struct timespec of differences and convert that difference to a double)

    Then things like

    double tstart = double_gettime(CLOCK_REALTIME);
    some_long_computation();
    double tend = double_gettime(CLOCK_REALTIME);
    printf ("needed %f seconds to compute\n", tend-tstart);
    

    See also clock(3)

提交回复
热议问题