通过JS测量CPU性能

12
一个 Web 应用程序的核心组件是一个处理几何运算的相对复杂的算法。
有两种解决方案,可以使整个应用程序在高端计算机和相对较慢的移动设备上都可以访问。如果检测到用户计算机“慢”,我可以使用 RPC(远程过程调用);否则,如果检测到用户计算机能够正常处理,则提供处理客户端的脚本给 Web 应用程序。
现在,有什么可靠的方法来检测用户机器的速度呢?
我想提供一个样本脚本作为测试,当页面加载时检测执行所需的时间。
有什么想法吗?
1个回答

12

我写了这个快速脚本来获取CPU速度:

var _speedconstant = 1.15600e-8; //if speed=(c*a)/t, then constant=(s*t)/a and time=(a*c)/s
var d = new Date();
var amount = 150000000;
var estprocessor = 1.7; //average processor speed, in GHZ
console.log("JSBenchmark by Aaron Becker, running loop " + amount + " times.     Estimated time (for " + estprocessor + "ghz processor) is " + (Math.round(((_speedconstant * amount) / estprocessor) * 100) / 100) + "s");
for (var i = amount; i > 0; i--) {}
var newd = new Date();
var accnewd = Number(String(newd.getSeconds()) + "." + String(newd.getMilliseconds()));
var accd = Number(String(d.getSeconds()) + "." + String(d.getMilliseconds()));
var di = accnewd - accd;
//console.log(accnewd,accd,di);
if (d.getMinutes() != newd.getMinutes()) {
  di = (60 * (newd.getMinutes() - d.getMinutes())) + di
}
spd = ((_speedconstant * amount) / di);
console.log("Time: " + Math.round(di * 1000) / 1000 + "s, estimated speed: " + Math.round(spd * 1000) / 1000 + "GHZ");

请注意,这取决于浏览器标签、内存使用等因素,但如果您只运行一次,比如在页面加载时,我发现它非常准确。
如果您愿意,可以更改 _speedconstant 以改变速度,只需使用方程式(已知CPU速度*已知完成时间)/已知周期计算即可。希望您会发现这很有用!

循环不执行任何操作。 - KevinBui

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接