Today I Learned - Rocky Kev

TIL High Resolution Time

POSTED ON:

TAGS:

I was reading about Javascript game design.

The Date object is no longer the recognized method for timing events because it is very imprecise and can be modified by the system clock.

TThe High Resolution Time API provides the current time in sub-millisecond resolution, more suitable for accurate timing than the Date functionality.It counts the number of milliseconds since navigationStart (when the previous document is unloaded).

With a good High Resolution Time implementation in setTimeout and setInterval, you can provide sub-millisecond accuracy to create a solid 60FPS framerate.

You may have also heard about the Performance API, or performance.now()?

It is a Performance API method that returns a DOMHighResTimeStamp (which stands for “High Resolution Time Stamp”), which, in simple words, is a time value in milliseconds in the fractional part between two points in time.

The most common use case for performance.now() is monitoring the time in which a piece of code is executed. Real life use cases could include benchmarking and monitoring performance of video, audio, games and other media.

We talked about the Date Object. Why can't it serve this need?

The biggest difference between performance.now() and Date.now() is that Date.now() returns a timestamp in relation to the Unix time (time passed from 00:00:00 UTC, 1 January 1970). This is where we potentially face an issue. How does JavaScript know how much time has elapsed since this date? It gets it from the system clock. But since the system clock lives in our machine, it can be adjusted manually or programmatically, therefore, time precision cannot be guaranteed.

via An Introduction to performance.now()

So how exactly do we use it?

const relativeTimestamp = performance.now();
const absoluteTimestamp = performance.timeOrigin + relativeTimestamp;
console.log(relativeTimestamp);
// 244.43500000052154
console.log(absoluteTimestamp);
// 1561926208892.4001

References:
w3 High Resolution Time
MDN Performance


Related TILs

Tagged:

TIL Dwarf Fortress Game Design

'Do not design for your experienced players' and some more tips from one of the most complicated games ever

TIL Breath of the Wild's many parameters

One of my favorite things to do is dig into how games are made on the data side.

TIL what a Shader is

Modern GPUs are incredibly flexible. Developers use shaders - to program the GPU to perform effects and complex rendering techniques. Devs write code in a shader language from an API (such as OpenGL) and a shader compiler in the video driver translates that code into binaries that your PC's GPU can run