Check the running time of a Javascript function

Asked

Viewed 4,229 times

6

I wonder if it is possible to know the running time of a certain javascript function..

This function does not need to bring external data, it can only handle form tags, set value, calculate fields, like this:

function idade(ano_aniversario, mes_aniversario, dia_aniversario) {
var d = new Date,
    ano_atual = d.getFullYear(),
    mes_atual = d.getMonth() + 1,
    dia_atual = d.getDate(),

    ano_aniversario = +ano_aniversario,
    mes_aniversario = +mes_aniversario,
    dia_aniversario = +dia_aniversario,

    quantos_anos = ano_atual - ano_aniversario;

if (mes_atual < mes_aniversario || mes_atual == mes_aniversario && dia_atual < dia_aniversario) {
    quantos_anos--;
}

return quantos_anos < 0 ? 0 : quantos_anos }
  • 2

    http://answall.com/questions/10660/%C3%89-poss%C3%Advel-obter-timestamps-com-precis%C3%A3o-de-fra%C3%A7%C3%B5es-de-milissegundos

3 answers

7


As Mr Angelo said, in modern browsers you can measure the elapsed time accurately by fractions of milliseconds using the object performance. The logic is the same as the other answers, but not to be repetitive I will suggest a generic function that measures the execution time of any other function that is passed (except asynchronous operations):

// Passe a função desejada. Se ela esperar parâmetros,
// passe os parâmetros na sequência. Exemplo:
// tempoDecorrido(minhaFuncao, 1, true, {teste:10});
function tempoDecorrido(funcao) {
    // pega os argumentos a serem repassados
    var args = Array.prototype.slice.call(arguments, 1);

    // logo antes da execução
    var inicio = performance.now();

    // executa a função passada, passando os argumentos se for o caso
    funcao.apply(null, args);

    // logo após a execução
    return performance.now() - inicio;
}

// Faz um loop de x a x+9
function minhaFuncao(x) {
    for(var i=x; i<x+10; i++) console.log(i);
}

// Testando
console.log(tempoDecorrido(minhaFuncao, 10));

  • Good, it becomes simpler to measure the execution without having to merge the "meter" in the code of the function to be analyzed.

  • I find this solution more interesting because then it is not necessary to repeat the duration calculation code in all functions, just call the function temp Run when and if necessary. This also means that existing functions will not need to be modified to calculate their durations.

3

To record the execution time, simply record the start and end within your target function.

With Javascript you can make use of the method getTime() of the object Date(), which returns the numeric value corresponding to the time for the specified date according to the universal time.

function tempoDecorrido() {

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

  var tempo = fim - inicio;

  alert('Tempo de execução: ' + tempo);
}


var inicio;

function idade() {

  inicio = new Date().getTime();

  /* a função deve ser chamada no fim da "idade", 
   * mas aqui chamamos após 1 segundo, para simular
   * que estivemos a trabalhar durante esse tempo
   */
  setTimeout(tempoDecorrido, 1000);
}

idade();

3

You can capture the start time of your method and remove the time that has passed from the current time until the end of the execution:


function seuMetodo()
{

var start = new Date();

for (var i=0; i<=30; i++) {
       console.log('mostra: '+i);
 }
var time = new Date() - start;
return 'tempo: '+time;
} 
seuMetodo();

Browser other questions tagged

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