# Calculate how long it takes to perform a function

5

I have to create a function in `JavaScript` that takes all the id's from a table and makes a draw with id's of the same table so that a same id does not fall with itself, and that there is a possibility that this id can being in the other "home".

exps:

``````1|2 - 2|1... válido.
1|1 - 2|2... inválido.
``````

In this way:

``````var teste = [];

for (var i = 1; i <= 305; i++) {
for (var x = 1; x <= 305; x++) {
if(x != i){
teste.push(i+'|'+x);
}
}
}
console.log(teste)``````

I would like to know if there is any way to know how long this function takes to run, since it generates more than 90,000 records.

asked by anonymous 26.03.2015 / 14:56

7

To measure the runtime, with resolution of milliseconds, just compare the timestamp before after execution:

``````function fn() {
var teste = [];

for (var i = 1; i <= 305; i++) {
for (var x = 1; x <= 305; x++) {
if(x != i){
teste.push(i+'|'+x);
}
}
}
}
var antes = Date.now();
fn();
var duracao = Date.now() - antes;
document.body.innerHTML = "levou " + duracao + "ms";``````

If your browser does not support `Date.now()` ( for example, IE8 or earlier), just use `new Date().getTime()` .

As for estimating the time it would take, before running, there I no longer know the answer. What you can estimate is the level of complexity, but the execution time will depend on several factors, I do not know if it is possible.

26.03.2015 / 15:09
7

To measure runtime you can use performance.now () , example:

``````var teste = [];
var inicio = performance.now();
for (var i = 1; i <= 305; i++) {
for (var x = 1; x <= 305; x++) {
if(x != i){
teste.push(i+'|'+x);
}
}
}

var fim = performance.now();
console.log(teste)
alert('Tempo de excução: ' + (fim - inicio));``````

Another option is console.time ()

``````var teste = [];
console.time('tempo');
for (var i = 1; i <= 305; i++) {
for (var x = 1; x <= 305; x++) {
if(x != i){
teste.push(i+'|'+x);
}
}
}
console.timeEnd('tempo');
console.log(teste)``````

26.03.2015 / 15:09