c - 分支预测器条目在程序完成后失效?

标签 c performance x86 branch-prediction spectre

我试图了解分支预测器条目何时无效。

以下是我所做的实验:

代码1:

start_measure_branch_mispred()
while(X times):
 if(something something):
  do_useless()
 endif
endwhile
end_measurement()
store_difference()

因此,我多次运行此代码。我可以看到,第一次运行后,错误预测率降低了。分支预测器学习如何正确预测。但是,如果我一次又一次地运行这个实验(即通过将 ./experiment 写入终端),所有第一次迭代都是从高误预测率开始的。因此,在每次执行时,那些条件分支的分支预测单元都会失效。我正在使用 nokaslr 并且禁用了 ASLR。我还在一个独立的核心上运行了这个实验。我已经运行了这个实验几次,以确保这是这种行为(即不是因为噪音)。

我的问题是:程序停止执行后,CPU 是否会使分支预测单元失效?或者说这是什么原因造成的?

我做的第二个实验是:

代码2:

do:
    start_measure_branch_mispred()
    while(X times):
      if(something something):
        do_useless()
      endif
    endwhile
    end_measurement()
    store_difference()
while(cpu core == 1)

在这个实验中,我从两个不同的终端运行不同的进程。第一个被固定到核心 1,以便它将在核心 1 上运行,并且它将执行此实验,直到我停止它(通过杀死它)。然后,我从另一个终端运行第二个进程,并将该进程固定到不同的内核。由于该进程位于不同的核心中,因此它只会执行 do-while 循环 1 次。如果第二个进程固定到第一个进程的同级核心(相同的物理核心),我发现在第一次迭代中,第二个进程的猜测几乎正确。如果我将第二个进程固定到不是第一个进程同级的另一个核心,那么第二个进程的第一次迭代会产生更高的错误预测。这是预期的结果,因为同一物理核心上的虚拟核心共享相同的分支预测单元(这是我的假设)。因此,第二个过程有利于经过训练的分支预测单元,因为它们具有相同的虚拟地址并映射到相同的分支预测单元条目。

据我了解,由于 CPU 尚未完成第一个进程(执行繁忙循环的核心 1 进程),因此分支预测条目仍然存在,第二个进程可以从中受益。但是,在第一个测试中,从一次到另一次运行,我得到了更高的错误预测。

编辑:由于其他用户要求提供代码,所以就在这里。您需要下载性能事件头代码from here

编译:$(CXX) -std=c++11 -O0 main.cpp -lpthread -o实验

代码:

#include "linux-perf-events.h"

#include <algorithm>
#include <climits>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <vector>

// some array
int arr8[8] = {1,1,0,0,0,1,0,1};

int pin_thread_to_core(int core_id){            
    int retval;     
    int num_cores = sysconf(_SC_NPROCESSORS_ONLN);      
    if (core_id < 0 || core_id >= num_cores)            
        retval = EINVAL;                                
    cpu_set_t cpuset;                                   
    CPU_ZERO(&cpuset);                                  
    CPU_SET(core_id, &cpuset);                          
    retval = pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
    return retval;
}

void measurement(int cpuid, uint64_t howmany, int* branch_misses){

    int retval = pin_thread_to_core(cpuid);
    if(retval){
        printf("Affinity error: %s\n", strerror(errno));
        return;
    }

    std::vector<int> evts;
    evts.push_back(PERF_COUNT_HW_BRANCH_MISSES); // You might have a different performance event!

    LinuxEvents<PERF_TYPE_HARDWARE> unified(evts, cpuid); // You need to change the constructor in the performance counter so that it will count the events in the given cpuid

    uint64_t *buffer = new uint64_t[howmany + 1];
    uint64_t *buffer_org; // for restoring
    buffer_org = buffer;
    uint64_t howmany_org = howmany; // for restoring

    std::vector<unsigned long long> results;
    results.resize(evts.size());

    do{
        for(size_t trial = 0; trial < 10; trial++) {

            unified.start();
            // the while loop will be executed innerloop times
            int res;
            while(howmany){
                res = arr8[howmany & 0x7]; // do the sequence howmany/8 times
                if(res){
                    *buffer++ = res;
                }       
                howmany--;
            }
            unified.end(results);
            // store misses
            branch_misses[trial] = results[0];
            // restore for next iteration
            buffer = buffer_org;
            howmany = howmany_org;
        }
    }while(cpuid == 5); // the core that does busy loop

    // get rid of optimization
    howmany = (howmany + 1) * buffer[3];
    branch_misses[10] = howmany; // last entry is reserved for this dummy operation

    delete[] buffer;

}
void usage(){
    printf("Run with ./experiment X \t where X is the core number\n");
}
int main(int argc, char *argv[]) {
    // as I have 11th core isolated, set affinity to that
    if(argc == 1){
        usage();
        return 1;
    }

    int exp = 16; // howmany

    int results[11];
    int cpuid = atoi(argv[1]); 

    measurement(cpuid, exp, results);

    printf("%d measurements\n", exp);

    printf("Trial\t\t\tBranchMiss\n");
    for (size_t trial = 0; trial < 10; trial++)
    {
        printf("%zu\t\t\t%d\n", trial, results[trial]);
    }
    return 0;
}

如果您想尝试第一个代码,只需运行 ./experiment 1 两次。它将与第一个代码执行相同的操作。

如果您想尝试第二个代码,请打开两个终端,在第一个终端中运行 ./experiment X,在第二个终端中运行 ./experiment Y ,其中 X 和 Y 是 cpuid。

请注意,您可能没有相同的性能事件计数器。另请注意,您可能需要更改 busyloop 中的 cpuid。

最佳答案

因此,我进行了更多实验来减少噪声的影响(从 _startmain() 函数或从 syscalls 和两个程序执行之间可能发生的中断(系统调用和中断)可能会破坏分支预测器。

这是修改后的实验的伪代码:

int main(int arg){ // arg is the iteration
   pin_thread_to_isolated_core()
   for i=0 to arg:
     measurement()
     std::this_thread::sleep_for(std::chrono::milliseconds(1)); // I put this as it is
   endfor
   printresults() // print after all measurements are completed
}

void measurement(){
   initialization()
   for i=0 to 10:
      start_measurement()
      while(X times) // for the results below, X is 32
        a = arr8[an element] //sequence of 8,
        if(a is odd)
           do_sth()
        endif
      endwhile
      end_measurement()
      store_difference()
   endfor
}

结果如下:

例如,我将迭代次数指定为 3

Trial           BranchMiss
RUN:1
    0           16
    1           28
    2           3
    3           1
    ....  continues as 1
RUN:2
    0           16   // CPU forgets the sequence
    1           30
    2           2
    3           1
    ....  continues as 1
RUN:3
    0           16
    1           27
    2           4
    3           1
    ....  continues as 1

因此,即使是毫秒的 sleep 也会干扰分支预测单元。为什么会这样?如果我不在这些测量之间设置 sleep ,CPU 可以正确猜测,即 Run2 和 Run3 将如下所示:

RUN:2
    0           1   
    1           1
    ....  continues as 1
RUN:3
    0           1
    1           1
    ....  continues as 1

我相信我减少了从 _start 到测量点的分支执行。尽管如此,CPU 仍然忘记了经过训练的东西。

关于c - 分支预测器条目在程序完成后失效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59143138/

相关文章:

assembly - 所有asm标签都成为可执行文件中的符号

计算 C 源代码中忽略注释和空行的行数

使用 libxml2 的 C 代码在 Win 7 上的 cygwin 上给出编译时错误

First() 与 Last() 在 SortedDictionary 上的性能

ios - SpriteKit : Collisions with 300 nodes, FPS 非常低

x86 - 多级分页如何节省内存?

我可以在 C 中将指针作为二维数组访问吗?

c - 可执行文件(用 C 语言编写)是否存在某种内存限制才能正常运行?

javascript - 处理 HTML/Javascript 中的数千个列表元素

c - 无用分配的Stackspace?