Why does this algorithm guarantee 60 updates per second?

82 Views Asked by At
run() {
    lastTime = currentTime();
    timer = currentTime();
    ns = 1000000000.0 / 60.0;

    delta = 0;
    frames = 0;
    updates = 0;

    while (true) {
        now = currentTime();
        delta += (now - lastTime) / ns;
        lastTime = now;
        while (delta >= 1) {
            updates++;
            delta--;
        }
        frames++;

        if (currentTime() - timer > 1000) {
            timer += 1000;
            print("FPS: " + frames + " UPS: " + updates);
            frames = updates = 0;
        }
    }
}

I don't understand the maths behind this algorithm. For some reason, it correctly outputs "UPS : 60" (updates per second) constantly.

Could someone explain it?

E: currentTime() just returns the current system time (measured from the moment the program is executed). If it helps, assume that the $i^\text{th}$ instruction takes $\delta_i>0$ seconds to execute.

E2: Still waiting for the reopening...