Calculate how long it takes to execute a function

Asked

Viewed 4,961 times

6

I have to create a function in JavaScript that takes all id’s from one table and makes a draw with id’s from the same table so that the same id does not fall with itself, and there is a possibility that that id may be in the other "house".

exps:

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

Thus:

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 wonder if there is any way to know how long this function takes to execute, since it generates more than 90 thousand records.

  • 1

    You want to measure runtime or estimate before running?

  • measure the run time according to the customer’s machine, but have an estimate tbm would come in handy rs

  • A +- off-topic question, a function that generates +- 90thousand records and takes 27ms can be considered slow?

  • I wouldn’t consider slow, especially when it comes to Javascript.

2 answers

8

To measure the running time 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 time console.(), example:

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)

  • 1

    That object performance, is very interesting, I didn’t know him. + 1 for the new knowledge.

  • 2

    Complement: console.time is not standard of W3C, and the performance object may not be available depending on browser + version. Then gets the hint of my reply, new Date().getTime() is the most compatible solution.

8


To measure runtime, with millisecond resolution, 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 how long it would take, before executing, then 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.

  • 1

    complexity level o(n 2) rs, for chained

Browser other questions tagged

You are not signed in. Login or sign up in order to post.