我有一个方法需要一段时间才能执行,我想计算执行方法需要多少时间:
var start = Date.now();
execute();
var final = Date.now();
var diff = final - start;
var seconds = diff / 1000;
var minutes = 0;
var hours = 0;
while(seconds >= 60)
{
minutes++;
seconds = Math.round(seconds/60);
}
while(minutes >= 60) {
hours++;
minutes = Math.round(minutes/60);
}
但我不能在几分钟和几秒钟内获得正确的信息。我的错误在哪里?
该方法需要1分几秒,但在日志中只显示20-40秒..
答案 0 :(得分:0)
在您的代码中,您应该减去它,而不是将秒数除以60。如果您的总时间为300秒,则在第一个循环中,您将秒数更新为5,而分钟将更新为1.
答案 1 :(得分:0)
startTime = Date.now();
execute();
endTime = Date.now();
totalSeconds = (endTime -startTime)/1000
hours = Math.floor(totalSeconds/3600)
minutes = Math.floor((totalSeconds%3600)/60)
seconds = Math.floor((totalSeconds%3600)%60)
console.log(hours, minutes, seconds)