Caculating function running time - javascript

I want to calculate the average running time of a function in JavaScript like this:
time = 0;
while(1000) {
time1 = performance.now();
function();
time2 = performance.now();
time += (time2-time1);
}
The problem is that only the first loop the time interval is about 60ms and the following loop the interval is nearly zero.
So I changed the code to:
time1 = performance.now();
while(1000000) {
function();
}
time2 = performance.now();
time = (time2-time1);
The running time is about 4 seconds.
I guess maybe it is because of the automatic optimisation.
If it is this case, are there any approaches to close the optimisation?

You've most likely caused the browser to hand off that code to its JIT compiler. The first run is always through the interpreter (slow). Hot code gets put through the JIT and the resulting native (fast) code is then used.
This is automatic and generally out of your hands to control. You can disable the Firefox JIT compiler by using 'with' in a script.
with({}) {}
Add this to the top of your script and the JIT will be disabled for your script.

You can also use console.time and console.endTime function to calculate the running time.
example:
console.time('profile 1');
for ( var i=0; i < 100000; i++) {
var arr = new Array();
}
console.timeEnd('profile 1');//profile 1: 108.492ms
console.time('profile 2');
for ( var i=0; i < 100000; i++) {
var arr = [];
}
console.timeEnd('profile 2');//profile 2: 81.907ms

Related

While not Stopping on Condition

how are you?
I am facing some issues with my code running on a snippet.
First: I do not know why when I try to run it, the loop does not finish
Second: One of my friends paste the code and ran on his computer and the loop finish but after running the second time the variables are sum with the new values inserted.
We are all using Google Chrome. Can anyone help me? Thanks.
var i = 0;
var speed = parseInt(prompt('value 1'));
var long = parseInt(prompt('value 2'));
var vel2 = velocidad;
while (speed> 0){
i++;
if (i>speed){
speed--;
}
console.log(speed);
}
sub_i = (i * vel2) - vel2;
console.log('Total i ' + i);
all you need is to initialize i = 0

Why the web worker version runs longer?

I'm trying to sum up numbers using two different variants, without web workers and using web workers.
I expect the web workers version to be about ten times faster because I divide the interval into ten intervals, but it's not like that. It's about ten times slower. I do not understand why. Does the ten web workers work in parallel?
var sum1 = 0, sum2 = 0, nrElements = 10000000;
var t0 = performance.now();
for (var i=0; i < nrElements; i++) {
sum1 += i;
}
var t1 = performance.now();
console.log("Version1 - " + (t1 - t0) + " sum: " + sum1)
var t3 = performance.now();
var n, running;
var pas = 0;
running = 0;
for (n = 0; n < 10; ++n) {
let workers = new Worker("worker.js");
pozStart = pas;
pas += nrElements / 10;
pozStop = pas;
workers.postMessage({start: pozStart, stop: pozStop});
workers.onmessage = workerDone;
++running;
}
function workerDone(e) {
--running;
sum2 += e.data[1];
if (running === 0) {
var t4 = performance.now();
console.log("Version2 - " + (t4 - t3) + " sum: " + sum2)
}
}
//worker.js
onmessage = function(e) {
var sum=0;
for(let i= e.data.start; i < e.data.stop; i++)
{
sum += i;
}
postMessage(["r",sum]);
}
There are many things here that could make your observations vary a lot, like how browsers do optimize your code (particularly for such simple for loops), but to answer the general question Why running through Web-Workers takes more time, then ...
You are running 10 workers in parallel. If your computer is not able to run ten threads concurrently, all your threads will indeed get slowed down.
As a rule of thumb, never exceed navigator.hardwareConcurrency- 1 number of concurrent Web Workers on the same page.
Initializing a WebWorker is not such a fast operation. It includes a Network request, parsing of the js file, building of the context. So initialize it once, and then ask them multiple times to do what you want.
But note that even then, you'll probably have slower results using the Workers with such a small operation. The simple operation
worker.postMessage(); // in main
self.onmessage = e => self.postMessage(); // in worker.js
worker.onmessage = e => ... // back in main
will already take place in at least 3 different event loops, since messages are received in the event loop following the one they've been sent from.
Unless you have some operations that will take seconds, offloading on worker might indeed get slower.
But even if slower, having your job offloaded in Worker allows the main thread to be free, and these 30ms will cause a drop of two frames, which could make something like an animation look jerky, so keep on using WebWorkers, but not for the speed.

How Can I make millisecond Unique?

I'm using NodeJs.
I received constantly request from server.
I'm added some variable like createdTime to it and saved to the database.
when I sorted data by createdTime in some case It is not reliable, It is Repeated
How can I make differentiate between them ?
I do not want to count request.
I do not like to change timestamp's format.
var createdTime = new Date().getTime();
Here's a method of combining a counter with the current time to allow you to have as many as 1000 separate transactions within the same ms that are all uniquely numbered, but still a time-based value.
And, here's a working snippet to illustrate:
// this guarantees a unique time-based id
// as long as you don't have more than 1000
// requests in the same ms
var getTransactionID = (function() {
var lastTime, counter = 0;
return function() {
var now = Date.now();
if (now !== lastTime) {
lastTime = now;
counter = 0;
} else {
++counter;
}
return (now * 1000) + counter;
}
})();
for (var i = 0; i < 100; i++) {
document.write(getTransactionID() + "<br>");
}
If you want something that is likely to work across clusters, you can use process.hrtime() to use the high resolution timer instead of the counter and then make the id be a string that could be parsed into a relative time if needed. Since this requires node.js, I can't make a working snippet here in the browser, but here's the idea:
// this makes a unique time-based id
function getTransactionID () {
var now = Date.now();
var hrtime = process.hrtime();
return now + "." + ((hrtime[0] * 1e9) + hrtime[1]);
}
Due to my low rep I can't add a comment but it looks like you are needing to go beyond milliseconds.Maybe this stackoverflow question can help you
How to get a microtime in Node.js?

window.performance.now() equivalent in nodejs?

I think the question is straight forward.
I'm looking for something that's similar to window.performance.now() in nodejs V8 engine.
Right now I'm just using:-
var now = Date.now();
//do some processing..
console.log("time elapsed:", Date.now() - now);
But, I read that window.performance.now() is lot more accurate than using the date because of the what's defined here.
Node v8.5.0 has added Performance Timing API, which includes the performance#now(), e.g.
const {
performance
} = require('perf_hooks');
console.log('performance', performance.now());
I would only mention that three of the reasons the author gives for the preference of the timing API in the browser wouldn't seem to apply directly to a node situation, and the fourth, the inaccuracy of Javscript time, cites an article from 2008, and I would strongly caution against relying on older material regarding Javascript performance specifics, particularly given the recent round of performance improvements all the engines have made to support "HTML5" apps.
However, in answer to your question, you should look at process.hrtime()
UPDATE: The present package (available via npm install present) provides some sugar around hrtime if you'd like it.
Note: Since the version 8.5.0 of Node, you can use performance.now()
Here's a shortcut for process.hrtime() that returns milliseconds instead of microseconds:
function clock(start) {
if ( !start ) return process.hrtime();
var end = process.hrtime(start);
return Math.round((end[0]*1000) + (end[1]/1000000));
}
Usage:
var start = clock();
// do some processing that takes time
var duration = clock(start);
console.log("Took "+duration+"ms");
Will output something like "Took 200ms"
What about?
console.time('FooTimer');
// do the work
console.timeEnd('FooTimer');
process.uptime()
Official Node Documentation
"The process.uptime() method returns the number of seconds the
current Node.js process has been running.
The return value includes fractions of a second. Use Math.floor() to
get whole seconds."
Example: Measure For Loop Execution Time
const nemo = ['nemo'];
function findNemo(array) {
let start_time = process.uptime();
for (let iteration = 0; iteration < array.length; iteration++) {
if (array[iteration] === 'nemo') {
console.log("Found Nemo");
}
}
let end_time = process.uptime();
console.log("For loop took this much time: ", end_time - start_time);
}
findNemo(nemo);
Example Output
Here's a Typescript version with process.hrtime(), based on NextLocal's answer:
class Benchmark {
private start = process.hrtime();
public elapsed(): number {
const end = process.hrtime(this.start);
return Math.round((end[0] * 1000) + (end[1] / 1000000));
}
}
export = Benchmark;
Usage:
import Benchmark = require("./benchmark");
const benchmark = new Benchmark();
console.log(benchmark.elapsed());
To sum up and avoiding using perf_hooks
const performance = {
now: function(start) {
if ( !start ) return process.hrtime();
var end = process.hrtime(start);
return Math.round((end[0]*1000) + (end[1]/1000000));
}
}
console.log('performance', performance.now());
This method came into existence in version 8.5.0 of nodejs https://nodejs.org/api/perf_hooks.html#perf_hooks_performance_measurement_apis
compare solutions with and without loop.
Note down, which makes a difference performance wise ?
Try it out in JS snippets in developer tools or any JS editor.
function sum(n) {
let total = 0;
for (let i = 0; i <= n; i++) {
total += i;
}
return total;
}
var t1 = performance.now();
sum(100000000);
var t2 = performance.now();
console.log(`time elapsed: ${(t2-t1)/1000} seconds.`);
function addupto(n) {
return n * (n + 1) / 2;
}
var t3 = performance.now();
addupto(100000000);
var t4 = performance.now();
console.log(`time elapsed: ${(t4-t3)/1000} seconds.`);

How to make a real Javascript timer

I'm looking for a way to manipulate animation without using libraries
and as usual I make a setTimeout in another setTimout in order to smooth the UI
but I want to make a more accurate function to do it, so if I want to make a 50ms-per-piece
animation, and I type:
............
sum=0,
copy=(new Date()).getMilliseconds()
function change(){
var curTime=(new Date()).getMilliseconds(),
diff=(1000+(curTime-copy))%1000 //caculate the time between each setTimeout
console.log("diff time spam: ",diff)
sum+=diff
copy=curTime
var cur=parseInt(p.style.width)
if (sum<47){//ignore small error
//if time sum is less than 47,since we want a 50ms-per animation
// we wait to count the sum to more than the number
console.log("still wating: ",sum)
}
else{
//here the sum is bigger what we want,so make the UI change
console.log("------------runing: ",sum)
sum=0 //reset the sum to caculate the next diff
if(cur < 100)
{
p.style.width=++cur+"px"
}
else{
clearInterval(temp)
}
}
}
var temp=setInterval(change,10)
I don't know the core thought of my code is right,anyone get some ideas about how to make a more accurate timer in most browser?
Set the JsFiddle url:
http://jsfiddle.net/lanston/Vzdau/1/
Looks too complicated to me, use setInterval and one start date, like:
var start = +new Date();
var frame = -1;
var timer = setInterval(checkIfNewFrame, 20);
function checkIfNewFrame () {
var diff = +new Date() - start;
var f = Math.floor(diff / 50);
if (f > frame) {
// use one of these, depending on whether skip or animate lost frames
++frame; // in case you do not skip
frame = f; // in case you do skip
moveAnimation();
}
}
function moveAnimation () {
... do whatever you want, there is new frame, clear timer past last one
}

Categories