![](/img/trans.png)
[英]Can I expect some heap memory locations to have faster access than others in C++?
[英]In C++, why am I finding heap memory accesses to be faster than stack acccesses
我一直在使用 C++ 中的分析器並注意到一些非常奇怪的東西:寫入堆 memory 比堆棧 memory 更快?
這是我跑的片段
#include <iostream> // std::cout
#include <chrono>
using namespace std;
const int size = 1000000;
void incStack(){
int seconds = 0;
for(int i = 0; i < size; i++){
seconds++;
}
}
void incHeap(){
int* seconds = new int(0);
for(int i = 0; i < size; i++){
(*seconds)++;
}
}
void testCycles(void (*func)(), string funcName){
int total = 0;
int count = 0;
for(int i = 0; i < 20; i++){
clock_t t = clock();
func();
t = clock() - t;
// we move the function to the cache on the first call which can possibly give
// us overhead, so we'll ignore the first call
if(i != 1){
total+= t;
count++;
}
}
cout << funcName << " cycles: " << total/count << endl;
}
int main() {
testCycles(incStack, "incStack");
testCycles(incHeap, "incHeap");
return 0;
}
與 output
incStack cycles: 1997
incHeap cycles: 1487
這非常重要,我意識到因為我只訪問堆上 memory 的一部分。 如果我訪問堆的許多部分,它可能總是在緩存中。 我假設我會因為 memory 可能會在堆上碎片化而遭受所有頁面交換到緩存的性能,但忽略所有這些。 堆應該至少有兩次訪問 memory (一個用於地址,一個用於地址值),這應該比堆棧花費更多的時間。
但是當我運行這段代碼時,堆訪問速度更快,所以我在 C++ 中遺漏了什么嗎? 我嘗試在一些編譯器上編譯並切換優化並得到類似的結果。 我真的很困惑為什么會這樣。
一般memory就是memory,CPU並不能真正區分。 但是,它確實關心如何訪問 memory。 在 C++ 中,您擁有三個工具:值、指針和引用。
直接價值總是最快的。 這些可能根本不存儲在 memory 中,而是寄存器,並且僅在必要時保存到 memory 中。 增加寄存器中的值將非常快。
間接值,如指針,涉及另一種訪問。 這些不能存儲在寄存器中,它們需要操作 CPU(內核)外部的值,希望在 L1 等某種緩存中。 一旦進入緩存,它就不會像主 memory 那樣慢,但總是比寄存器慢。
引用是常規值的一種別名,因此它們應該也可以執行,但這取決於您的代碼在編譯時的優化程度。 在經過高度優化的構建(如-O3
或等效版本)下,這些通常可以在寄存器中分流,而不是實際命中 memory。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.