Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 24th, 2012  |  syntax: None  |  size: 1.73 KB  |  hits: 17  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #include <signal.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <inttypes.h>
  6. #include <limits.h>
  7. #include <stdlib.h>
  8.  
  9. #define TIMES SHRT_MAX
  10. uint64_t rdtsc(void) {
  11.     uint32_t lo,hi; __asm__ __volatile__ ("xorl %%eax,%%eax\ncpuid" ::: "%rax", "%rbx", "%rcx", "%rdx");
  12.     __asm__ __volatile__("rdtsc" : "=a"(lo), "=d"(hi));
  13.     return (uint64_t)hi << 32 | lo;
  14. }
  15.  
  16. void __attribute__ ((noinline)) *rep_movsb(void *dst, const void *src, size_t cnt)
  17. {      
  18.         /*
  19.          * "rep movs"  is optimized in  microcode on
  20.          * modern  Intel  CPU's.  This  method works
  21.          * best for easy-copys (src-alligned?), this
  22.          * will give best  performance if src & dst
  23.          * are both equal (mod 64).  But  will still
  24.          * work if they're not.  This method is also
  25.          * faster than any SSE routine.
  26.          *
  27.          * See: https://lkml.org/lkml/2011/9/1/229
  28.          * for more information regarding the matter.
  29.          */
  30.         __asm__("cld; rep movsb" ::
  31.                 "c"(cnt),
  32.                 "S"(src),
  33.                 "D"(dst)
  34.         );
  35.         return dst;
  36. }
  37.  
  38. void __attribute__ ((noinline)) eat_it(void* eat) { (void)eat; }
  39.  
  40. int main(int argc, char **argv)
  41. {
  42.         if (argc < 2)
  43.                 return 0;
  44.  
  45.         int size = atoi(argv[1]);
  46.        
  47.         char *buf1;//[16384];
  48.         char *buf2;//[16384];
  49.         char *buf3;//[16384];
  50.         char *buf4;//[16384];
  51.  
  52.         buf1 = buf2 = buf3 = buf4 = malloc(size);
  53.         uint64_t s1,s2;
  54.         int i;
  55.         for(;;)
  56.         {
  57.                 s1 = rdtsc();
  58.                 for (i=0;i<TIMES; i++) {
  59.                         rep_movsb(buf1, buf2, size);
  60.                         rep_movsb(buf2, buf1, size);
  61.                         eat_it(buf3);
  62.                         eat_it(buf4);
  63.                 }
  64.                 printf("movsb:  %ld (cpu cycles)\n", rdtsc()-s1);
  65.                 s2 = rdtsc();
  66.                 for (i=0;i<TIMES; i++) {
  67.                         memcpy(buf3, buf4, size);
  68.                         memcpy(buf4, buf3, size);
  69.                         eat_it(buf3);
  70.                         eat_it(buf4);
  71.                 }
  72.                 printf("memcpy: %ld (cpu cycles)\n", rdtsc()-s2);
  73.         }
  74. }