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 @TFConsult: Celebrating 100th birthday of #physicist #RichardFeynman: The marvellous #Feynman lectures on #physics: https://t.co/81as7mN
About 1 week, 4 days ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @sergerey: Had a fantastic time giving our workshop on Spatial Data Science with PyData at @GeoPythonConf with @levijohnwolf. Looking f…
About 1 week, 5 days ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @fridex: Everything has an end even such an excellent conference #GeoPythonConf in Basel. Thanks to organizers for such an outstanding c…
About 1 week, 5 days 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