我想了解CPU缓存利用率。为此,我编写了一小段 Node.js 代码:
let testArray = [];
let length = "";
let times = "";
do {
testArray.push(Math.random());
if (testArray.length % 1000 === 0) {
testArray = testArray.slice();
const start = performance.now();
action(testArray);
const stop = performance.now();
const duration = stop - start;
length += testArray.length + "," + endOfLine;
times += duration + "," + endOfLine;
console.log(`Took: ${duration}, length: ${testArray.length}`);
}
}
while (testArray.length < 10000000)
function action(a) {
let sum = 0;
for (let index = 0; index < 10000; index++) {
sum += a[index];
}
}
我希望函数调用的持续时间与此图表类似:
尽管我有预期,无论数组的大小是多少,持续时间都几乎相同。我认为随着数组变大,它将超过 L1、L2 和 L3 缓存,我会在图表上看到它。
我的代码是错误的还是我遗漏了什么?
我不知道评论者在说什么。 Javascript 数组不是“真正的”数组,它们只是奇特的对象。 Javascript 对象在数组方面有两个问题:
转到不同的语言。 Javascript是一种脚本语言,属于容易学习的类别,它不太适合CS概念。您可能能感受到 CPU 实际缓存任何内容的差异的唯一方法是通过
array buffers
。