Overv / Open.GL

The source code and content of Open.GL.
http://open.gl/
1.07k stars 259 forks source link

Using clock() to get time yields incorrect result #37

Closed lewtds closed 9 years ago

lewtds commented 9 years ago

In the Drawing Polygons chapter, the color animation is made dependent of time by dividing clock() by CLOCKS_PER_SEC. This is an obsolete method to get the elapsed time as per POSIX, CLOCKS_PER_SEC is always defined as 1000000, regardless of the actual clock ticks per second. On my machine, for example (Arch Linux 64-bit, Intel processor), this animation is extremely slow.

The recommended approach is to use clock_gettime(), like this:

#include <time.h>

...

struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
float time = t.tv_sec + t.tv_nsec / 1e9;
Overv commented 9 years ago

I've solved this by using the chrono standard library as such:

#include <chrono>

...

auto t_start = std::chrono::high_resolution_clock::now();

...

auto t_now = std::chrono::high_resolution_clock::now();
float time = std::chrono::duration_cast<std::chrono::duration<float>>(t_now - t_start).count();

Seems like the most portable and correct solution.