I'm looking into the speed of JavaScript parsers in web browsers, importantly it needs to be easy to demonstrate. I came up with a simple test - the idea being that each script block is parsed and executed individually, so a large block of script could be timed:
<script>var start = new Date().getTime();</script>
<script>
/*! jQuery v1.8.2 jquery.com | jquery.org/license */
...
</script>
<script>alert ( new Date().getTime() - start );</script>
Superficially this appears to work, removing the middle script block will result in a negligible time.
However I'm not certain that my logic is not fundamentally flawed.
It seems the answer is broadly yes, but to get a reasonable result (like anything else) the test should be run many times to level out the effects of compilation caching and garbage collection. The test above can easily be placed into the Parse-n-Load library: http://carlos.bueno.org/2010/02/measuring-javascript-parse-and-load.html
Thanks for your help
This may be of help!
var start = new Date().getTime();
var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);
If you want to benchmark your JavaScript, include MilliSeconds etc.
var t = new Date();
var start = t.getTime()*1000 + t.getMilliseconds();
/* do something*/
var t2 = new Date();
var end = t2.getTime()*1000 + t.getMilliseconds();
alert("The Code needed " + (end-start) + " milliseconds. That are " + parseInt((end-start)/1000) + " seconds.");
You might want to differentiate between parsing and execution time. You could do something like
<script>start = Date.now();</script>
<script>
parsed = Date.now();
/*! jQuery v1.8.2 jquery.com | jquery.org/license */
…
</script>
<script>var end = Date.now();
alert ( "parsed in " + (parsed - start) + "ms" );
alert ( "executed in " + (end - parsed) + "ms" );
alert ( "overall time: " + (end - start) + "ms" );
</script>
With that you might be able to detect cached parse trees etc. Yet, for more distinct information have a look at your developer tools, they show such type of information in their profiler section. Or in Opera, it's included in the load process of scripts in the network panel.
This answer is from 10 years in the future.
There are a number of approaches to timing web page processes including:
Date-related methods:
Date.now();
and:
console.time-related methods:
console.time('myTimer');
console.timeLog('myTimer');
console.timeEnd('myTimer');
but, since late 2015, the ideal way to time web page processes using high-resolution timestamps has been:
window.performance.now();
Using Performance:
The Performance interface, accessed via window.performance has numerous methods, including:
timeOrigin
mark
measure
getEntries
toJSON
and more.
But in order to time a script, all you need is window.performance.now():
let scriptStart = window.performance.now();
let scriptEnd = window.performance.now();
let scriptDuration = (scriptEnd - scriptStart);
Working Example:
let paragraph = document.querySelector('p');
let button = document.querySelector('button');
const runTimedScript = () => {
let scriptStart = window.performance.now();
for (let i = 0; i < 10000; i++) {
paragraph.textContent = 'Loop iteration ' + (i + 1);
}
let scriptEnd = window.performance.now();
let scriptDuration = (scriptEnd - scriptStart);
button.textContent = 'Re-run Script';
console.log('The script ran in ' + scriptDuration + ' milliseconds');
}
button.addEventListener('click', runTimedScript, false);
button {
cursor: pointer;
}
<p></p>
<button type="button">Run Script</button>
<p>To see how long the script takes to run,<br />
click the button above repeatedly.</p>
Further Reading:
To find out more about the Performance Interface, see:
Performance API (MDN)
Related
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?
While profiling my web app in Chrome I found that the following function function was taking a large percentage of the total runtime for my app (which is reasonable considering how often it is used - maybe 1000 times each page load). I therefore wonder if anyone has any suggestions of how it could be improved to increase the performance?
function getDate(dateString) {
re = dateString.split(/\-|\s/);
return new Date(re.slice(0, 3).join('/') + ' ' + re[3]);
}
This function is given a string in the form: "YYYY-MM-DD HH:MM:SS", for example: "2014-06-06 23:45:00", and returns a Javascript date.
I am using jQuery so that is an option.
Checkout the following code:
function getDate(dateString) {
re = dateString.split(/\-|\s/);
return new Date(re.slice(0, 3).join('/') + ' ' + re[3]);
}
function getDate2(d) {
return new Date(
d.substr(0, 4) +
'/' +
d.substr(5, 2) +
'/' +
d.substr(8, 2) +
' ' +
d.substr(11, 8)
);
}
function getDate3(d) {
return new Date(d);
}
function benchmark(func, times) {
var start = new Date();
for (var i = 0; i < times; i++) {
var temp = eval(func);
}
var end = new Date();
console.log(func + 'took ' + (end - start) + ' microseconds to execute ' + times + ' times.');
}
var str = '2014-06-06 23:45:15';
benchmark("getDate(str)", 1000000);
benchmark("getDate2(str)", 1000000);
benchmark("getDate3(str)", 1000000);
This gave me the following results:
LOG: getDate(str)took 2215 microseconds to execute 1000000 times.
LOG: getDate2(str)took 940 microseconds to execute 1000000 times.
LOG: getDate3(str)took 270 microseconds to execute 1000000 times.
So, you can see the regex engine takes a high penalty in Javascript. Using substr reduces the execution time by more than 50%, and using the direct string (which is valid in modern Javascript runtimes) reduces the execution time by almost 90%. :-)
Not using that many array operations, and especially not using a global re variable, should help:
function getDate(dateString) {
return new Date(dateString.replace(/-/g, "/"));
}
However, notice that YYYY-MM-DD HH:MM:SS is a valid date format which will be parsed by the Date constructor directly (OK, maybe not in older IEs), but in a standard browser this will work as well:
function getDate(dateString) {
return new Date(dateString);
}
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.`);
The following code is from 'JavaScript by Example Second Edition',I think the code below is better
function scroller() {
str = str.substring(1, str.length) + str.substring(0, 1);
document.title = str;
window.status = str;
}
setInterval(scroller, 300);
The old code is recursive and will continue to call itself every 0.3 seconds until the program ends, I think the old code maybe cause stack overflow, right?
<html>
<!-- This script is a modification of a free script found at
the JavaScript source.
Author: Asif Nasir (Asifnasir#yahoo.com)
-->
<head>
<script type="text/javascript">
var today = new Date();
var year = today.getFullYear();
var future = new Date("December 25, " + year);
var diff = future.getTime() - today.getTime();
// Number of milliseconds
var days = Math.floor(diff / (1000 * 60 * 60 * 24));
// Convert to days
var str =
"Only " + days + " shopping days left until Christmas!";
function scroller() {
str = str.substring(1, str.length) + str.substring(0, 1);
document.title = str;
window.status = str;
setTimeout(scroller, 300); // Set the timer
}
</script>
</head>
<body onload="scroller()">
<b>
<font color="green" size="4">
Get Dizzy. Watch the title bar and the status bar!!
<br />
<image src="christmasscene.bmp">
</font>
</body>
</html>
setInterval is good if you don't care too much about accuracy, e.g. polling for some condition to be met.
setTimeout is good if you want a one–off event or need to adjust the interval between calls, e.g. a clock that should update as close as possible to just after the next whole second.
Both can be used for events that run continuously at approximately the specified interval, both can be cancelled, both only run at about (as soon as possible after) the designated time interval.
Incidentally, the first code example in the OP should not cause a stack overflow, though it is otherwise not very well written.
Have a look here:
'setInterval' vs 'setTimeout'
setTimeout runs the code/function once after the timeout.
setInterval runs the code/function in intervals, with the length of
the timeout between them.
For what you're doing, you should be using setInterval.
I'm trying to build a POC to migrate a heavy JSF application to a stateless ajax/restful application .
In the proccess i can't decide what is the best way of presenting the JSON data returned to the screen , i can see 2 major approaches one is to have templates and use something like prototype's toHTML() with them and the other is to build the objects in javascript and then use appendchild .
the first one is much more easy to understand for a new person who has to maintain the code as the templates are very clear and easier to maintain (allso the skills needed to change the html in templates are lower) but from what i understand the appendchild method is better in regards to browser speed .
what is the preferable way to handle this and am i missing other points of comparison between the two ?
append child is this a good compromise between the two ?
are there any other ways to do this ?
P.S : to be clear i'm talking about client side manipulations only
Setting html directly with innerHTML is the fastest way cross-browser. It has some bugs, however, that you should keep in mind (tables, forms, etc.).
var html = [];
for (...) {
html.push( PARTIAL_HTML );
}
element.innerHTML = html.join("");
UPDATE: The best way may be to test it for yourself:
function test( name, fn, n, next ) {
var n = n || 100; // default number of runs
var start, end, elapsed;
setTimeout(function() {
start = Number(new Date());
for ( ; n--; ) {
fn()
}
end = Number(new Date());
elapsed = end - start;
// LOG THE RESULT
// can be: $("#debug").html(name + ": " + elapsed + " ms");
console.log(name + ": " + elapsed + " ms"));
next && next();
}, 0);
}
test("dom", function() {
// ...
});
test("innerHTML", function() {
// ...
});