【问题标题】:How to check how much time executes javascript function? [duplicate]如何检查执行javascript函数的时间? [复制]
【发布时间】:2014-08-01 15:42:24
【问题描述】:

我不知道该怎么做。 Javascript是单线程的,所以我不能同时运行函数和定时器。如何查看我的函数执行了多少时间?

【问题讨论】:

  • 使用console.time('identifier')console.timeEnd('identifier')
  • 您可以将其作为节点进程 node 运行并使用 unix 的 time 命令。
  • 关于另一篇文章的注意事项:如果函数是异步的,则应捕获 end 并在回调内部进行比较。

标签: javascript time


【解决方案1】:

您可以使用Date 对象的getTime() 方法。

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

for (var i = 0; i < 100000; ++i) {
    // work
}

var end = new Date().getTime();
var time = end - start;
console.log('Execution time: ' + time);

start 是代码开始执行的时刻。 end 是它完成执行的时刻。如果您在这 2 个时刻之间有所不同,您就会得到执行所需的时间。

此外,考虑到在 javascript 中您可以将函数作为参数传递,您可以执行以下操作:

function profile(myCode) {
    var start = new Date().getTime(); //the moment when execution starts

    myCode(); //execute your code

    var end = new Date().getTime(); // the moment when execution finishes
    var time = end - start; // time it took
    console.log('Execution time: ' + time); // output the time to console
    return time; // return the time for further use
}

【讨论】:

  • 能否解释一下反对意见,以便我改进我的答案?
  • 大概我明白了。我的问题最近被标记为欺骗,您似乎已从原始问题中复制了已接受的答案。
  • 我没有复制任何答案。另外,我没有看到它被标记为欺骗。它可能类似于其他答案,因为它只有 3 行代码。哦,好吧。
  • “另外,我没有看到它被标记为欺骗” - ??
  • 您的问题在哪里被标记为重复?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-28
  • 2016-02-07
  • 2019-03-30
  • 1970-01-01
  • 2011-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多