Node.js 和 CPU 缓存利用率

问题描述 投票:0回答:1

我想了解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];
    }
}

我希望函数调用的持续时间与此图表类似:

enter image description here

尽管我有预期,无论数组的大小是多少,持续时间都几乎相同。我认为随着数组变大,它将超过 L1、L2 和 L3 缓存,我会在图表上看到它。

我的代码是错误的还是我遗漏了什么?

node.js memory cpu-cache
1个回答
0
投票

我不知道评论者在说什么。 Javascript 数组不是“真正的”数组,它们只是奇特的对象。 Javascript 对象在数组方面有两个问题:

  1. 数据位于内存中的随机位置,这意味着实际上与 CPU 缓存没有相关性(对于每个索引,您都必须跳过指针,几乎没有缓存);
  2. 因为它们是数组列表,又名对象,所以它们需要一个内存消耗非常大的哈希表(我讨厌)。

转到不同的语言。 Javascript是一种脚本语言,属于容易学习的类别,它不太适合CS概念。您可能能感受到 CPU 实际缓存任何内容的差异的唯一方法是通过

array buffers

© www.soinside.com 2019 - 2024. All rights reserved.