检测进程所用时间的JavaScript代码

JavaScript Code to Detect Time a Process Took

本文关键字:JavaScript 代码 时间 进程 检测      更新时间:2023-09-26

所以在我的JavaScript文件中,我试图让它检测加密/解密需要多长时间,并将其链接起来,但时间有点偏离了这就是代码,

 var stop = new Date();
 var time = (stop-start) % 1000;
 if(time < 10) var ms = "00"+time;
 else if((time < 100) && (time >= 10)) var ms = "0"+time;
 else var ms = time;
 var s = Math.floor((stop-start) / 1000);
 if(document.forms['timer'].elements[0].checked == true)
 document.forms['timer'].elements[1].value = s+":"+ms;
 else document.forms['timer'].elements[1].value = "";

这给了我这样的答案1327851955:962关于它所花的时间,而大多数时间我相信它只花了不到一秒钟,所以如果你不介意,有人能解释一下如何修复它吗?

如果你只需要它来调试,使用谷歌Chrome开发工具,你有一些非常好的方法;

console.time('encryption')您想开始测量时间,console.timeEnd('encryption')您想结束时间。

您还可以使用其他一些很棒的控制台工具,例如配置文件方法

console.profile('encryption')->console.profileEnd('encryption')然后转到Profiles选项卡,以便能够调试代码的CPU性能,并找到任何瓶颈和需要改进的地方

我不太明白你的代码想要实现什么,但你可以计算做这样的事情所需的时间:

var startTime = new Date().getTime();
//insert a call to do your encryption/decryption here..
var endTime = new Date().getTime();
console.log("The encryption/decryption took: " + (endTime - startTime) + "ms.");