JavaScript microsecond

Are there any sync functions in JavaScript with microsecond resolution?

I know timer.js for Chrome, and I hope that there will be a solution for other friendly browsers such as Firefox, Safari, Opera, Epiphany, Konqueror, etc. I'm not interested in supporting IE, but answers, including IE, are welcome.

(Given the low accuracy of millisecond time in JS, I can't hold my breath!)

Update: timer.js advertises the resolution in microseconds, but simply multiplies the millisecond by 1000. It is verified by checking and verifying the code. Disappointed .: [

+65
javascript
Jun 04 2018-11-11T00:
source share
4 answers

As mentioned in Mark Reichon's answer, modern browsers have an API that provides time synchronization data of up to milliseconds for a script: W3C High Resolution timer , aka window.performance.now() .

now() better than traditional Date.getTime() two important ways:

  • now() is double with a submillismodule resolution, which is the number of milliseconds since the start of page navigation. It returns the number of microseconds in fractional (for example, a value of 1000.123 is 1 second and 123 microseconds).

  • now() monotonously increasing. This is important because Date.getTime() can jump forward or even backward on subsequent calls. It is noteworthy that if the system time of the OS is updated (for example, synchronization of atomic clocks), Date.getTime() also updated. now() guaranteed to grow monotonously, so the OS system time does not affect it - there will always be a wall clock time (if your wall clock is not atomic ...).

now() can be used in almost every place where new Date.getTime() , + new Date and Date.now() . The exception is that Date and now() times do not mix, since Date based on unix-epoch (the number of milliseconds since 1970), and now() is the number of milliseconds since the start of navigation on your page (therefore it will be much less than Date )

now() supported in Chrome stable, Firefox 15+, and IE10. There are also several polyps .

+85
Jan 14 '14 at 18:14
source share

Now a new microsecond measurement method has appeared in javascript: http://gent.ilcore.com/2012/06/better-timer-for-javascript.html

However, in the past I found a crude method for getting 0.1 millisecond precision in JavaScript from a millisecond timer. Impossible? Nope. Continue reading:

I am doing experiments with a high degree of accuracy that require a self-monitoring accuracy of the timer, and I found that I was able to reliably obtain 0.1 millisecond accuracy with some browsers on certain systems.

I found that in modern accelerators with GPU acceleration on fast systems (for example, i7 quad core, where several cores are idle, only a browser window) - now I can trust timers with millisecond accuracy. In fact, it became so accurate on an unoccupied i7 system that I was able to reliably get the same millisecond for more than 1000 attempts. Only when I try to do something like loading an additional web page or another, the accuracy in milliseconds deteriorates (And I can successfully catch my degraded accuracy by checking before and after the time to see my processing time suddenly increased to 1 or more milliseconds - this helps me to invalidate the results, which are probably too much affected by CPU fluctuations).

It became so accurate in some accelerated GPU browsers on quad-core i7 systems (when the browser window is the only window) that I found, I would like to access the 0.1 ms precision timer in JavaScript, since the accuracy finally appeared in some high-performance viewing systems to make such timer accuracy appropriate for certain types of niche applications requiring high accuracy, and where applications can independently check for accuracy deviations.

Obviously, if you are doing multiple passes, you can simply start multiple passes (e.g. 10 passes) and then divide by 10 to get an accuracy of 0.1 milliseconds. This is a general method of obtaining better accuracy - to complete several passes and divide the total time by the number of passes.

HOWEVER ... If I can only make one control pass of a particular test because of an unusually unique situation, I found out that I can get an accuracy of 0.1 (and sometimes 0.01 ms) by doing the following:

Initialization / Calibration:

  • Start the busy cycle to wait until the timer expands to the next millisecond (align the timer before the start of the next millisecond interval). This busy cycle lasts less than a millisecond.
  • Run another busy cycle to increase the counter while waiting for the timer to increase. The counter tells you how many counter increments occurred in one millisecond. This busy cycle lasts one millisecond.
  • Repeat the above until the numbers become ultra-stable (load time, JIT compiler, etc.). 4. NOTE. Room stability gives you achievable accuracy on an unoccupied system. You can calculate the variance if you need to check the accuracy yourself. Deviations are greater in some browsers and less in other browsers. More on faster systems and slower on slower systems. Consistency is also changing. You can determine which browsers are more consistent / accurate than others. Slower systems and busy systems will lead to large differences between initialization passes. This may enable you to display a warning message if the browser does not give you sufficient accuracy to measure 0.1 ms or 0.01 ms. A timer failure may be a problem, but some whole millisecond timers on some systems grow quite accurately (exactly right at a point), which will lead to very stable calibration values ​​that you can trust.
  • Save the final counter value (or the average value of the last calibration passes)

Comparing one pass to the nearest millisecond:

  • Start a busy cycle to wait until the timer expands to the next millisecond (align the timer before the start of the next millisecond interval). This busy cycle lasts less than a millisecond.
  • Complete the task for which you want to determine the exact time.
  • Check the timer. This gives you whole milliseconds.
  • Start the last busy cycle to increase the counter, waiting for the timer to increase. This busy cycle lasts less than a millisecond.
  • Divide the value of this counter by the initial value of the counter from initialization.
  • Now you got the decimal part of milliseconds !!!!!!!!

WARNING. Busy cycles are NOT recommended in web browsers, but, fortunately, these busy cycles are less than 1 millisecond each and run only a few times.

Variables, such as JIT compilation and CPU fluctuations, add huge inaccuracies, but if you run several initialization passes, you will have full dynamic recompilation, and, ultimately, the counter will plunge into something very accurate. Make sure that all employment cycles are exactly the same function for all cases, so that differences in employment cycles do not lead to differences. Make sure that all lines of code are executed several times before you start trusting the results so that the JIT compilers are already stabilized to full dynamic recompilation (dynarec).

In fact, I have witnessed the accuracy of the approaching microseconds on some systems, but I would still not trust this. But 0.1 millisecond accuracy seems to work quite reliably in a simple quad-core system, where I am the only browser page. I came to a scientific test case where I could only make one-time passes (due to unique variables) and was required exactly for each pass, and not to average several repeated passes, so I did it.

I made several preliminary passes and dummy passes (also for dynarec calculation) to check the accuracy of 0.1 ms (remained solid for several seconds), and then held my hands off the keyboard / mouse, then performed several post-passes to check the accuracy 0.1 ms (remained solid again). It also verifies that things like changing nutritional status or other things did not occur between before and after, interfering with the results. Repeat the preliminary test and post test between each pass of the test. After that, I was pretty sure that the results between them were accurate. Of course, there is no guarantee, but this shows that in some cases accuracy of <0.1ms is possible in a web browser.

This method is only useful in very, very niche cases. However, this literally will not be 100% infinitely guaranteed, you can get very reliable accuracy and even scientific accuracy in combination with several levels of internal and external checks.

+14
Oct 26 '12 at 15:17
source share

The answer is no, in general. If you use JavaScript in some server environment (that is, not in the browser), then all bets are disabled, and you can try to do whatever you want.

edit - this answer is old; standards have progressed and new possibilities have emerged as a solution to the exact time problem. However, it should be remembered that outside the real-time real-time operating system realm, ordinary unprivileged code has limited control over access to computing resources. Performance measurement is not the same (required) as performance forecasting.

+3
Jun 04 2018-11-11T00:
source share

Here is an example showing my high resolution timer for node.js :

  function startTimer() { const time = process.hrtime(); return time; } function endTimer(time) { function roundTo(decimalPlaces, numberToRound) { return +(Math.round(numberToRound + `e+${decimalPlaces}`) + `e-${decimalPlaces}`); } const diff = process.hrtime(time); const NS_PER_SEC = 1e9; const result = (diff[0] * NS_PER_SEC + diff[1]); // Result in Nanoseconds const elapsed = result * 0.0000010; return roundTo(6, elapsed); // Result in milliseconds } 

Using:

  const start = startTimer(); console.log('test'); console.log(`Time since start: ${endTimer(start)} ms`); 

You can usually use:

  console.time('Time since start'); console.log('test'); console.timeEnd('Time since start'); 

If you define sections of code that are associated with a loop, you cannot access the value of console.timeEnd() to add the results of the timer together. You can, but it becomes unpleasant, because you need to enter the value of your iterating variable, for example i , and set a condition to determine if the loop is complete.

Here is an example because it might be useful:

  const num = 10; console.time(`Time til ${num}`); for (let i = 0; i < num; i++) { console.log('test'); if ((i+1) === num) { console.timeEnd(`Time til ${num}`); } console.log('...additional steps'); } 

Cite: https://nodejs.org/api/process.html#process_process_hrtime_time

0
Jul 05 '17 at 3:06 on
source share



All Articles