perlopenglglutgettimeofdaytime-hires

gettimeofday time difference is occasionally negative


I'm writing an Object Oriented OpenGL framework in perl and I'm running into a weird issue when I measure the DeltaTime between each frame. The delta time seems to go negative every once in a while (every ~.5 seconds). I'm not sure if this is gettimeofday's problem or if it's a problem with how GLUT calls my callbacks, but it's pretty annoying because it makes the movement of my sprite jump slightly every half a second.

Here's my glut main loop function:

# This is called everytime in the main glut loop
sub Tick
{
    my $this = shift;
    my ($now, $dt);

    $now = gettimeofday;
    $dt = $now - $this->{_oldTime};

    if ($dt < 0)
    {
        my $dterr;

        $dterr = $now - $this->{_oldErrorTime};

        print "WTF! We just encountered a time paradox! " . 
            "This function was last called $dt seconds ago...\n" .
            "Current time: $now, Last call: $this->{_oldTime}\n" .
            "We already encountered this error $dterr seconds ago.\n\n";

        $this->{_oldErrorTime} = $now;
    }

    $this->{_oldTime} = $now;
    $this->{FPS} = 1.0 / $dt;

    $this->Update($dt);
    $this->DrawFrame($dt);
}

And here's the output:

WTF! We just encountered a time paradox! This function was last called -0.017144 9184417725 seconds ago... Current time: 1340196716.27624, Last call: 1340196716.29339 We already encountered this error 0.482785940170288 seconds ago.

WTF! We just encountered a time paradox! This function was last called -0.013265 84815979 seconds ago... Current time: 1340196716.74632, Last call: 1340196716.75959 We already encountered this error 0.470081090927124 seconds ago.

WTF! We just encountered a time paradox! This function was last called -0.011317 9683685303 seconds ago... Current time: 1340196717.21836, Last call: 1340196717.22968 We already encountered this error 0.472035884857178 seconds ago.

WTF! We just encountered a time paradox! This function was last called -0.015201 0917663574 seconds ago... Current time: 1340196717.68649, Last call: 1340196717.70169 We already encountered this error 0.468127012252808 seconds ago.


Solution

  • You need CLOCK_MONOTONIC, see Time::HiRes.