Dominik Pastierovič
Dominik Pastierovič

Reputation: 33

Memory in cache in C

Is there some way to find out if memory I have requested is cached or not? And if so, it would be helpful to know in which level of cache is that chunk of memory stored.

I had an idea that adress of pointer might change when its cached but it looks like that doesnt work.

Edit: it is for university project and I have access to multiple machines with different OSs so almost any solution would help.

Upvotes: 3

Views: 7501

Answers (2)

I had an idea that adress of pointer might change when its cached but it looks like that doesnt work.

You probably misunderstand how caching works. Caching is a separate memory, yes, and it has it's own addresses, but when the CPU caches memory lines from RAM, it keeps a record of what RAM-addresses the memory was on, and keeps a map between RAM-address and cache-address. From the point of view of your program, the address is the same. If your program requires an address, and the CPU sees that address in the map (a cache hit, a success), the CPU translates the address on the fly and gets the data from cache instead of from RAM.

Is there some way to find out if memory I have requested is cached or not?

From a high level language (like C), no there is not. The operating system can theoretically (depending on CPU architecture) find out if addresses are cached, but this is not anything you can rely on with C.

See Can i check if a chunk of memory (e.g., allocated using malloc) stays in the cache?

Upvotes: 5

alseether
alseether

Reputation: 1993

If you have already requested any memory chunk, for sure is cached.

When any memory address is requested, a check in first cache level is made, if it fails, then a check in second level and so on.

Once the block where that address belongs to is found, the whole block is placed inside first level of cache, due to principle of locality, in order to avoid additional searches for the same block (for instance, if you access the same address or consecutive ones) which is common in almost every program (for loops, indexes, etc)

Upvotes: 1

Related Questions