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

前端 未结 5 817
误落风尘
误落风尘 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:36

    If you are trying to force something to be stored in the CPU cache, I would recommend that you avoid trying to do so unless you have an overwhelmingly good reason. Manually manipulating the CPU cache can have all sorts of unintended consequences, not the least among them being coherency in multi-core or multi-CPU applications. This is something that is done by the CPU at run-time and is generally transparent to the programmer and the compiler for a good reason.

    The specific answer will depend on your compiler and platform. If you are targeting a MIPS architecture, there is a CACHE instruction (assembly) which allows you to do CPU cache manipulations.

提交回复
热议问题