title: Speed of memcpy() greatly influenced by different ways of malloc()
body: <p>I wrote a program to test the speed of <code>memcpy()</code>. However, how memory are allocated greatly influences the speed. </p>
  
  <h1>CODE</h1>
  
  <pre><code>#include&lt;stdlib.h&gt;
  #include&lt;stdio.h&gt;
  #include&lt;sys/time.h&gt;
  
  void main(int argc, char *argv[]){
      unsigned char * pbuff_1;
      unsigned char * pbuff_2;
      unsigned long iters = 1000*1000;
  
      int type = atoi(argv[1]);
      int buff_size = atoi(argv[2])*1024;
  
      if(type == 1){ 
          pbuff_1 = (void *)malloc(2*buff_size);
          pbuff_2 = pbuff_1+buff_size;
      }else{
          pbuff_1 = (void *)malloc(buff_size);
          pbuff_2 = (void *)malloc(buff_size);
      }   
  
      for(int i = 0; i &lt; iters; ++i){
          memcpy(pbuff_2, pbuff_1, buff_size);
      }   
  
      if(type == 1){ 
          free(pbuff_1);
      }else{
          free(pbuff_1);
          free(pbuff_2);
      }   
  }
  </code></pre>
  
  <p>The OS is linux-2.6.35 and the compiler is GCC-4.4.5 with options "-std=c99 -O3". </p>
  
  <p>Results on my computer(<code>memcpy</code> 4KB, iterate 1 million times):</p>
  
  <p>time ./test.test 1 4</p>
  
  <pre><code>real    0m0.128s
  user    0m0.120s
  sys 0m0.000s
  </code></pre>
  
  <p>time ./test.test 0 4</p>
  
  <pre><code>real    0m0.422s
  user    0m0.420s
  sys 0m0.000s
  </code></pre>
  
  <p>This question is related with a previous question:</p>
  
  <p><a href="https://stackoverflow.com/questions/21038965/why-speed-of-memcpy-drops-dramatically-every-4kb">Why does the speed of memcpy() drop dramatically every 4KB?</a></p>
  
  <h1>UPDATE</h1>
  
  <p>The reason is related with GCC compiler, and I compiled and run this program with different versions of GCC:</p>
  
  <p>GCC version--------<code>4.1.3</code>--------<code>4.4.5</code>--------<code>4.6.3</code></p>
  
  <p>Time Used(1)-----<code>0m0.183s</code>----<code>0m0.128s</code>----<code>0m0.110s</code></p>
  
  <p>Time Used(0)-----<code>0m1.788s</code>----<code>0m0.422s</code>----<code>0m0.108s</code></p>
  
  <p>It seems GCC is getting smarter.</p>