title: C Program to determine Levels & Size of Cache
body: <p><strong>Full Re-Write/Update for clarity (and your sanity, its abit too long) ...</strong> (<a href="https://stackoverflow.com/revisions/12594208/3">Old Post</a>)</p>
  
  <p>For an assignment, I need to find the levels (L1,L2,...) and size of each cache. Given hints and what I found so far: I think the idea is to create arrays of different sizes and read them. Timing these operations: </p>
  
  <pre><code>sizes = [1k, 4k, 256K, ...]
  foreach size in sizes 
      create array of `size`
  
      start timer
      for i = 0 to n // just keep accessing array
          arr[(i * 16) % arr.length]++ // i * 16 supposed to modify every cache line ... see link
      record/print time
  </code></pre>
  
  <p><strong>UPDATED (28 Sept 6:57PM UTC+8)</strong></p>
  
  <p>See also <strong><a href="https://gist.github.com/3787223#file_cache_profile.c" rel="noreferrer">full source</a></strong></p>
  
  <p>Ok now following @mah's advice, I might have fixed the SNR ratio problem ... and also found a method of timing my code (<code>wall_clock_time</code> from a lab example code)</p>
  
  <p>However, I seem to be getting incorrect results: I am on a Intel Core i3 2100: [<strong><a href="http://www.cpu-world.com/CPUs/Core_i3/Intel-Core%20i3-2100%20CM8062301061600.html" rel="noreferrer">SPECS</a></strong>]</p>
  
  <ul>
  <li>L1: 2 x 32K </li>
  <li>L2: 2 x 256K</li>
  <li>L3: 3MB</li>
  </ul>
  
  <p>The results I got, in a graph: </p>
  
  <p>lengthMod: 1KB to 512K</p>
  
  <p><img src="https://i.stack.imgur.com/5Ee0m.png" alt="enter image description here"></p>
  
  <p>The base of the 1st peak is 32K ... reasonable ... the 2nd is 384K ... why? I'm expecting 256? </p>
  
  <p>lengthMod: 512k to 4MB</p>
  
  <p><img src="https://i.stack.imgur.com/LzgAE.png" alt="enter image description here"></p>
  
  <p>Then why might this range be in a mess? </p>
  
  <hr>
  
  <p>I also read about prefetching or interference from other applications, so I closed as many things as possible while the script is running, it appears consistently (through multiple runs) that the data of 1MB and above is always so messy? </p>