Estimated completion time of forEach() method - javascript

I have a forEach() method that looks like this:
channels.forEach((channel) => {
var start = new Date().getTime();
fields.forEach(function(field) {
//stuff done here
});
var end = new Date().getTime();
var time = (end - start);
console.log(time)
});
I'd like to take the execution time for the first channel in the forEach() method, and estimate the rest of the loops based on that first completion time. Not sure if this is set up correctly for that, or where I should go from here

It is fundamentally correct, but you are printing the elapsed time of each channel, instead of just once, unless you are cancelling the test afterwards. I would suggest that you measure the time it takes to run over all the channels and take the average time for all, as this value will be more consistent/scientific for lack of a better word.
Also, the regular Date().getTime() function only has a precision down to one millisecond. You could switch to a library with a more precise nanosecond timer.

Try it with console.time() and console.timeEnd() as shown below:
channels.forEach((channel) => {
console.time("time taken");
fields.forEach(function(field) {
//stuff done here
});
console.timeEnd("time taken");
});

Related

Is there a way to watch times with moment.js and run a function when it does?

I'm new to moment.js and javascript and I couldn't seem to find anything in moment.js documentation or other questions here. I am comparing two different times, and would like to watch the time and run a function when Time A is equals to Time B.
so something like:
var a = TimeA
var b = TimeB
//watch the current time
when a === b {
//run a function
}
else {
//do nothing
}
There are many ways you can do this. But the most traditional way is to use an Interval Function as Badgy has pointed. Here is an working example for a 1 second interval:
var timeA = moment().add(10, 'seconds'); // 10 seconds from now
var tmr = setInterval(()=>{
var now = moment().unix();
var then = timeA.unix();
console.log(now, then)
if (now >= then) {
clearInterval(tmr);
console.log('Whatever you want to do');
}
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
I used .unix() method in moment.js because it returns the time in seconds. So it's better for comparison with the first time than a string like '2013-02-04T22:44:30.652Z' or the isSame() method because it uses milliseconds and can skip the exact moment. A second is a large enough time unit so it can be compared to the current time.
You could make a interval function and check every second if the times equal each other. Also throw a look at this it may help too.

function efficiency measuring javascript

I would like to check the efficiency of my functions, let's say to find a prime number, I wrote something like:
var counter = 0;
var myVar = setInterval(myTimer, 10)
function myTimer() {counter++}
//Function to be accessed
function isPrime(num){
my function
}
var prime = isPrime(x);
clearInterval(myVar);
console.log(counter);
My problem is that counter = 0in the end
Interestingly it would work if I would make an action with the timer, for example getting an html element and increase it's value.
Any idea?
thanks
//start timer with label
console.time("label");
doSomething();
//end timer and print to corresponding label
console.timeEnd("label");
function doSomething()
{
alert("stackoverflow bye!");
}
In cases where you have to measure performance console.time() and console.timeEnd() is your friend.
console.time(string) starts timer
console.timeEnd(string) ends timer and print in console
You should be aware of event loops in javascript to understand why your code didn't work as expected. The rule number 1 of event loop is, functions which are gonna work in async manner would be pushed in callBack queue. And the other functions would be pushed into call stack. Once all the functions in call stack got executed then only the functions in callBack queue will be executed one by one. No matter how much waiting time you gave.
.
.
var myVar = setInterval(myTimer, 10);
//myTimer will be put under a timer internally
//And will wait for 10 ms to enter into callBack queue
//Say this was happened in 1st millisecond
.
.
.
var prime = isPrime(x);
//isPrime(x) will be pushed into call stack and executed immediately
//if there is no other function in the stack
//Say this was happened in 5th millisecond
.
.
.
clearInterval(myVar);
//clearInterval(myVar) will be pushed into call stack and executed immediately
//if there is no other function in the stack.
//And simultaneously kill the timer which was created internally.
//Say this was happened in 7th millisecond
.
.
console.log(counter);
//Now, there was not at all a single chance to call the function myTimer.
//So the counter variable wouldn't be incremented.
//Thus it prints 0.
To do a proper instrumentation, you have to use the date object.
function isPrime(num){}
var prime, startTime, endTime;
startTime = Date.now();
prime = isPrime(x);
endTime = Date.now();
console.log(endTime - startTime, "ms taken to finish execution");
I can't exactly understand you're target. If you want to check how fast youre methods are set a timestamp, run the method and waiting for a callback. If its arrived set a new timestamp and compare both.

Write a function that checks how many times another function will be called in a time interval

Say I have a function that logs "Hello" every 500 ms.
var logHello = function() {
setInterval(function(){
console.log("Hello");
}, 500);
};
Is there a way to write another function that will check if logHello gets called more than or equal to 1 time every second(without modifying the original logHello function).
In this case it will return true because Hello will get logged 2 times in 1 seconds.
I am assuming you want to do this for debug reasons, so I must warn you not to include this code in any production application, as it's really just meant for debugging. It's very cool that our solution works however it overwrites native javascript functionality which is typically frowned upon because it can cause code to behave differently than expected if you alter a native functions behaviour.
If it's a condition that you are not allowed to modify your code, you can simply overwrite javascript's setInterval, and use it as a "hook" into your function. We will modify setInterval to now track the time difference (seconds) inbetween calls to your method. We will then invoke and return the original setInterval method so that your code still works exactly as expected:
// keep a pointer to the original setInterval function
var oldSetInterval = window.setInterval;
// we will create our own setInterval function and put logging in it
window.setInterval = function(block, interval) {
var lastRunAt;
return oldSetInterval(function() {
// here is where we print how long it's been since the method last ran
if(lastRunAt) {
console.log("the interval last ran " + (Date.now()-lastRunAt)/1000 + " seconds ago");
}
lastRunAt = Date.now();
block();
}, interval);
}
And now running logHello() yields:
Hello
the interval last ran 0.504 seconds ago
Hello
the interval last ran 0.504 seconds ago
Hello
the interval last ran 0.505 seconds ago
This assumes you're running on the web. If you're in node, replace references to window with globals.

Benchmark javascript execution with callback functions

I have some JavaScript that I'm trying to benchmark the time it takes to execute.
The problem with this is that the for loop completes quickly, meanwhile the execution of the Item.save() method is not yet complete.
Any suggestions how to time this that takes into account the full execution time within the contents of the loop?
Thank you!
var start = new Date().getTime();
var Item = new Item();
for (i = 0; i < 500; i++) {
var item = {};
item.name = 5;
item.id = 10;
item.set = [];
Item.save(item, function (err, res) {
console.log(res);
});
}
var elapsed = new Date().getTime() - start;
console.log(elapsed);
EDIT: This is on a nodejs server.
Just use Chrome's profiling tools. They give you total insight into exactly how much CPU time every function call on your page is taking up:
http://code.google.com/chrome/devtools/docs/cpu-profiling-files/two_profiles.png
For Node, you can try node-inspector's experimental profiler.
The best way to handle this would be to modify the Item.save() function to take in the start time and then do your comparison at the very end. Or, implement a callback function (succes:) on Item.save().
The answer is simple: create a jsPerf test case. It allows running asynchronous or “deferred” tests.
Alternatively, you could use Benchmark.js and set up a deferred test case manually.
Don’t simply compare two new Date timestamps, as that only works for synchronous tests. (Also, this is not an accurate way of measuring things across all browsers and devices.)

Is calling setTimeout with a negative delay ok?

The following snippet sets a timeout that I'd like to last at least a second:
var currentTimeMillis = new Date().getTime();
// do stuff...
var sleepTime = 1000 - (new Date().getTime() - currentTimeMillis);
Given that sleepTime can be a negative number, is it safe to call setTimeout, like this:
setTimeout(callback, sleepTime)
Or do I need to check for negative values before calling setTimeout?
According to the MDN reference, the specification requires that there is a minimum timeout.
If you provide something less than this (HTML5 spec says 4ms) then the browser will just ignore your delay and use the minimum.
So negatives should be fine, since it'll just be less than the minimum.
Apparently, this isn't always the case (isn't that always the way with web development!). According to ( http://programming.aiham.net/tag/browser-compatibility/ ):
Providing setTimeout a negative time will not always result in the
callback function being called. This works in other browsers, but in
Internet Explorer (8 or lower) you have to make sure any negative
times are changed to zero.
I haven't tested this myself, but like Thomasz said, it's probably better to be safe.
Better be safe than sorry:
setTimeout(callback, Math.max(sleepTime, 0))
You could also use a conditional statement, like so:
if (sleepTime < 0) {
sleepTime = 0;
}
setTimeout(callback, sleepTime);
Hmm... The solutions mentioned solves the problem at the call to setTimeout, so it needs to be written each time a call is made. Isn't it better to solve it directly in setTimeout?
// Run this once.
(function(){
var oldSetTimeout = setTimeout
setTimeout = function(callback, delay){
return oldSetTimeout(callback, Math.max(delay, 0))
}
})()
// Call setTimeout safely with a negative delay.
setTimeout(function(){ console.log("Hello World") }, -42)
Yes it is ok to use negative timeout in milli-seconds like this.
setTimeout(() => {
btn.style.top = '16.2%';
btn.style.left = '35.8%';
btn.style.transition = 'all 1.2s ease';
},-1.2*1000);
This code will initiate transition on button of id btn after 1.2*1000 seconds of delay,style top and style left

Categories

Resources