2016-09-12 29 views
0

你能告訴我如何使用clflush()指令嗎?我已經編寫了下面的簡單代碼來測量從緩存中讀取變量的執行時間和從緩存中逐出後的執行時間之間的差異。但是我沒有找到確鑿的結果。什麼是使用clflush()驅逐緩存的正確方法?CLFLUSH()的問題?

  #include <stdio.h> 
      #include <stdint.h> 
      #include"cpucycles.c" 

      #define REPEAT 1900000 
      inline void clflush(volatile void *p) 
      { 
       asm volatile ("clflush (%0)" :: "r"(p)); 
      } 

      inline uint64_t rdtsc() 
      { 
       unsigned long a, d; 
       asm volatile ("cpuid; rdtsc" : "=a" (a), "=d" (d) : : "ebx", "ecx"); 
       return a | ((uint64_t)d << 32); 
      } 

      volatile int i; 

      inline void test() 
      { 
       uint64_t start, end,clock; 
       volatile int j; 
       long int rep; 
       int k; 

       clock=0; 
       for(rep=0;rep<REPEAT;rep++){ 
        start = rdtsc(); 
        j = i+1; 
        end = rdtsc(); 
        clock=clock+(end-start); 
        k=j; 
       } 
       printf("took %lu ticks\n", clock); 
      } 

      inline void testflush() 
      { 
       uint64_t start, end,clock; 
       volatile int j; 
       int k; 
       long int rep; 

       clock=0; 
       for(rep=0;rep<REPEAT;rep++){ 
        start = rdtsc(); 
        j = i+1; 
        end = rdtsc(); 
        clflush(&i); 
        clock=clock+(end-start); 
        k=j; 
       } 
       printf("took %lu ticks\n", clock); 
      } 


      int main(int ac, char **av) 
      { 
       i=5; 
       printf("------------------------------------------\n"); 
       test(); 
       printf("------------------------------------------\n"); 
       testflush(); 
       printf("------------------------------------------\n"); 
       test(); 

       return 0; 
      } 
+1

[如何使用clflush?]的可能重複(http://stackoverflow.com/questions/39448276/how-to-use-clflush) – Olaf

回答

0

看起來你的'同花順'時間正在被代碼的其餘部分淹沒。此外,正如您所寫的,您的非flush會執行更少的代碼行(不刷新),從而使比較「不公平」。

怎麼樣更多的東西一樣:

#include <stdio.h> 
#include <stdint.h> 
#include <malloc.h> 
#include <emmintrin.h> 

#define REPEAT 1900000 

volatile int i; 

inline void test(void *v) 
{ 
    uint64_t start, end; 
    volatile int j; 
    long int rep; 
    int k; 

    start = __builtin_ia32_rdtsc(); 
    for(rep=0;rep<REPEAT;rep++){ 
     j = i+1; 
     _mm_clflush(v); 
     k=j; 
    } 
    end = __builtin_ia32_rdtsc(); 
    printf("%p took %lu ticks\n", v, end-start); 
} 

int main(int ac, char **av) 
{ 
    void *v = malloc(1000); 
    i=5; 
    printf("------------------------------------------\n"); 
    test(v); 
    printf("------------------------------------------\n"); 
    test((void *)&i); 
    printf("------------------------------------------\n"); 
    test(v); 
    free(v); 

    return 0; 
} 

這樣,我們總是在沖洗一些東西,但一個測試會影響你的全球性的,其他沒有。它也不使用任何內聯彙編。

使用-O3構建,這使我獲得149次非flush和312次flush的時間。