Vedad
Vedad

Reputation: 223

Why does this code generates a cache hit many times?

I understand the concept of cache hit and miss, but somehow I don't really get it on code Examples. The following code should generate many catch Hits, but why? In what part we see that? How we now that this code will finde most of the time the data in the cache?

char array[1000]; 
for ( int i=0; i<1000; i++ ){ 
printf("%d ", array[i]); 
}

Upvotes: 0

Views: 120

Answers (1)

Grzegorz Szpetkowski
Grzegorz Szpetkowski

Reputation: 37954

The given code is a perfect example of spatial locality of reference, because array[i] is accessed in continous and forward manner. According to Wikipedia:

Spatial locality

If a particular storage location is referenced at a particular time, then it is likely that nearby memory locations will be referenced in the near future. In this case it is common to attempt to guess the size and shape of the area around the current reference for which it is worthwhile to prepare faster access.

You might also note that i variable exhibits temporal locality, in which case it's likely that it will be placed by optimizing compiler into a CPU register.

Upvotes: 1

Related Questions