Is there a way to force a variable to be stored in the cache in C?

前端 未结 5 815
误落风尘
误落风尘 2021-02-05 23:55

I just had a phone interview where I was asked this question. I am aware of ways to store in register or heap or stack, but cache specifically?

5条回答
  •  隐瞒了意图╮
    2021-02-06 00:45

    As cache is a CPU concept and is meaningless for C language (and C language has targets processors that have no cache, unlikely today, but quite common in old days) definitely No.

    Trying to optimize such things by hand is also usually a quite bad idea.

    What you can do is keep the job easy for the compiler keeping loops very short and doing only one thing (good for instruction cache), iterate on memory blocks in the right order (prefer accesses to consecutive cells in memory to sparse accesses), avoid reusing the same variables for different uses (it introduces read-after-write dependencies), etc. If you are attentive to such details the program is more likely to be efficiently optimized by compiler and memory accesses be cached.

    But it will still depend on actual hardware and even compiler may not guarantee it.

提交回复
热议问题