指针间接多少影响效率? [英] How much does pointer indirection affect efficiency?

查看:97
本文介绍了指针间接多少影响效率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解除引用指针的速度慢于直接访问该值?我想我的问题是 - 参考运算符有多快?

Is dereferencing a pointer notabley slower than just accessing that value directly? I suppose my question is - how fast is the deference operator?

推荐答案

>由于现代CPU的工作原理慢得多。但它与运行时内存无关。

Going through a pointer indirection can be much slower because of how a modern CPU works. But it has nothing much to do with runtime memory.

相反,速度受到预测和缓存的影响。

Instead, speed is affected by prediction and cache.

当指针未被改变或以可预测的方式改变时(例如,在循环中递增或递减4),预测是容易的。这允许CPU基本上在实际代码执行之前运行,确定指针值将是什么,并将该地址加载到高速缓存中。

Prediction is easy when the pointer has not been changed or when it is changed in predictable ways (for example, increment or decrement by four in a loop). This allows the CPU to essentially run ahead of the actual code execution, figure out what the pointer value is going to be, and load that address into cache. Prediction becomes impossible when the pointer value is built by a complex expression like a hash function.

缓存开始起作用,因为指针可能指向不在缓存中的内存并且它必须被提取。如果预测工作,但如果预测不可能,则这被最小化,在最坏的情况下,你可以有双重影响:指针不在缓存中,指针目标也不在缓存中。在最坏的情况下,CPU会停止两次。

Cache comes into play because the pointer might point into memory that isn't in cache and it will have to be fetched. This is minimized if prediction works but if prediction is impossible then in the worst case you can have a double impact: the pointer is not in cache and the pointer target is not in cache either. In that worst-case the CPU would stall twice.

如果指针用于函数指针,CPU的分支预测器就会起作用。在C ++虚拟表中,函数值都是常量,预测变量很容易。当执行间接跳转时,CPU将使代码准备好运行并在流水线中。但是,如果它是一个不可预测的函数指针,则性能影响可能很大,因为流水线将需要刷新,每次跳转会浪费20-40个CPU周期。

If the pointer is used for a function pointer, the CPU's branch predictor comes into play. In C++ virtual tables, the function values are all constant and the predictor has it easy. The CPU will have the code ready to run and in the pipeline when execution goes through the indirect jump. But, if it is an unpredictable function pointer the performance impact can be heavy because the pipeline will need to be flushed which wastes 20-40 CPU cycles with each jump.

这篇关于指针间接多少影响效率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆