User Tools

Site Tools


Sidebar

General

Python Tutorials

WebGL Tutorials

Node.js Tutorials

Node.js in WebStorm


Martin Christen

View Martin Christen's profile on LinkedIn


Twitter

Timeline of @MartinChristen

MartinChristen avatar

RT @snebiker: #PlayGameLieschtel - brilliant event by Kantonsbibliothek Baselland #KBL to get kids into libraries, including family #gamede…
About 2 days, 13 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

Only a handful tickets left for @PyConDE in Karlsruhe (October 24-28, 2018) - The schedule is now available at… https://t.co/Og4fp3DsoA
About 5 days, 6 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

IAMCP & @swissmade_sw Augmented Reality event just started https://t.co/bdREI6lJM4 #ar #AugmentedReality #Basel… https://t.co/9KpsdU3fvM
About 6 days, 12 hours ago by: Martin Christen (@MartinChristen)
node:tutorial04

Node.js Tutorials - Part 0

Node.js Tutorial 4

Timing is a very important task when optimizing your code. There are several ways to time your code. In this tutorial 3 ways of timing are presented.

1. Timing using console.time()

One of the easiest ways of timing is using the functions console.time and console.timeEnd.

console.time takes a label as parameter. When you call console.timeEnd with the same label it outputs the time passed since calling console.time with same label. An example is:

console.log('Timer example: console.time');

console.time('measure_sum');

var sum = 0;
for (var i=0; i<100000;i++) {
	for (var j=0;j<1000;j++) {
  	sum += (i+j);
  }
}

console.log('sum='+sum);
console.timeEnd('measure_sum');

The output of this example is:

Timer example: console.time
sum=5049900000000
measure_sum: 830ms

2. Timing using Date().getTime()

Another way of measuring time is using the getTime() function of the Date object.

Our example would look like this:

console.log('Timer example: Date().getTime()');

var ts0 = new Date().getTime();

var sum = 0;
for (var i=0; i<100000;i++) {
	for (var j=0;j<1000;j++) {
  	sum += (i+j);
  }
}

console.log('sum='+sum);
var ts1 = new Date().getTime();
console.log(ts1-ts0);

3. High Precision Timing using process.hrtime()

Using process.hrtime() it is possible to measure in nanosecond resolution. The above example modified for hrtime looks like this:

console.log('Timer example: process.hrtime()');

var th = process.hrtime();

var sum = 0;
for (var i=0; i<100000;i++) {
	for (var j=0;j<1000;j++) {
  	sum += (i+j);
  }
}

console.log('sum='+sum);
th = process.hrtime(th);

console.log('Time: %d seconds and %d nanoseconds', th[0], th[1])


node/tutorial04.txt · Last modified: 2013/09/16 22:05 by mchristen