我试图得到函数battle2运行多长时间的平均值。这是我的一个小小的个人项目的一部分,用于测试编写代码的不同方式如何影响时间效率(我是初学者)。这似乎适用于n< = 3但完全崩溃的任何高于那个(理想情况下我有n = 100)并且我无法弄清楚为什么除了可能那个battle2已经包含一个for循环并且放一个on它的顶部放慢了太多?感谢您的任何见解!
第二个问题:特别是这个代码没有发生,但有时当我在较小的代码片段上使用performance.now()时,它会记录为0毫秒...?这是因为它发生得如此之快,电脑无法记录时间或其他东西?
//Second version of my rock, paper, scissors function
function battle2(p1, p2){
var shoot = ["rock", "scissors", "paper"];
for (i = 0; i < 3; i++){
if (p1 === shoot[i] && p2 === shoot[(i + 2) % 3]){
return "p2";
}
else if (p1 === shoot[i] && p2 === shoot[(i + 1) % 3]){
return "p1";
}
if (p1 === p2 ){
return "p0";
}
}
}
//Create empty array and sum variables to collect values each pass of the
loop
n = 4
var array2 = [];
var sum2 = 0;
//Repeat the code below this line n times
for (i = 0; i < n; i++){
//Randomly generate p1 and p2 choice each time through the loop
var choicesB = ["rock", "scissors", "paper"];
var randomB = Math.floor(Math.random()*3);
var random2B = Math.floor(Math.random()*3);
p1 = choicesB[randomB];
p2 = choicesB[random2B];
//Check performance on battle2 each time through the loop
var start2B = performance.now();
battle2(p1,p2);
var duration2B = performance.now() - start2B;
//Sometimes performance.now() logs as 0 (why?), so I ignore those instances
here
if (duration2B !== 0){
array2.push(duration2B);
sum2 += duration2B;
}
}
var average2 = sum2/array2.length;
console.log(average2)