Re: gettimeofday day returning same value; possible bug or?

  • From: Finn Wilcox <finnw@xxxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Tue, 24 Jul 2012 14:50:59 +0100

On 24/07/2012 13:49, Chris wrote:
I reduced the problem down to the following code:


local ffi = require'ffi'

    struct timeval {
       uint32_t sec;
       uint32_t usec;

    int gettimeofday(struct timeval *restrict tp, void *restrict tzp);

local tp ="struct timeval")

function gettime()
    ffi.C.gettimeofday(tp, nil)
    --print("***", tp.sec, tp.usec)
    return tp.sec + (tp.usec / 1000000)

Other than the bug that Mike just confirmed, there are a few other things you need to look out for:

1. On some 64-bit platforms (e.g. Darwin), timeval.sec is a uint64_t. If this is the case then tp.sec + (tp.usec / 1000000) will also truncate to a uint64_t so you will lose the fractional part and it will measure only whole seconds. 2. tp.sec + (tp.usec / 1000000) exceeds the precision of double-precision floating point, so you will lose some bits anyway. If you intend to use this timer for profiling (which involves adding lots of small intervals together) the errors will accumulate rapidly.

You might want to define a function that returns the difference in microseconds between two timevals instead. e.g.

    function elapsed_usecs(start, finish)
        local s = tonumber(finish.sec - start.sec)
        local us = tonumber(finish.usec - start.usec)
        return s * 1000000 + us


Other related posts: