繁体   English   中英

测量C ++代码的CPU周期

[英]Measure the CPU cycles of C++ code

我的目标是使用简单的代码来衡量(不同)缓存的效果。 我正在关注这篇文章,特别是第20和21页: https : //people.freebsd.org/~lstewart/articles/cpumemory.pdf

我正在使用64位linux。 L1d缓存为32K,L2为256K,L3为25M。

这是我的代码(我使用不带标志的g ++编译此代码):

#include <iostream>

// ***********************************
// This is for measuring CPU clocks
#if defined(__i386__)
static __inline__ unsigned long long rdtsc(void)
{
    unsigned long long int x;
    __asm__ volatile (".byte 0x0f, 0x31" : "=A" (x));
    return x;
}
#elif defined(__x86_64__)
static __inline__ unsigned long long rdtsc(void)
{
    unsigned hi, lo;
    __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
    return ( (unsigned long long)lo)|( ((unsigned long long)hi)<<32 );
}
#endif
// ***********************************


static const int ARRAY_SIZE = 100;

struct MyStruct {
    struct MyStruct *n;
};

int main() {
    MyStruct myS[ARRAY_SIZE];
    unsigned long long cpu_checkpoint_start, cpu_checkpoint_finish;

    //  Initializing the array of structs, each element pointing to the next 
    for (int i=0; i < ARRAY_SIZE - 1; i++){
        myS[i].n = &myS[i + 1];
        for (int j = 0; j < NPAD; j++)
            myS[i].pad[j] = (long int) i;
    }
    myS[ARRAY_SIZE - 1].n = NULL;   // the last one
    for (int j = 0; j < NPAD; j++)
        myS[ARRAY_SIZE - 1].pad[j] = (long int) (ARRAY_SIZE - 1);

    // Filling the cache
    MyStruct *current = &myS[0];
    while ((current = current->n) != NULL)
        ;

    // Sequential access
    current = &myS[0];

    // For CPU usage in terms of clocks (ticks)
    cpu_start = rdtsc();

    while ((current = current->n) != NULL)
        ;

    cpu_finish = rdtsc();

    unsigned long long avg_cpu_clocks = (cpu_finish - cpu_start) / ARRAY_SIZE;

    std::cout << "Avg CPU Clocks:   " << avg_cpu_clocks << std::endl;
    return 0;
}

我有两个问题:

1-我将ARRAY_SIZE从1更改为1,000,000(因此,阵列的大小在2B到2MB之间),但是平均CPU时钟始终为​​10。

根据该PDF文件(第21页的图3-10),当阵列完全适合L1时,我希望获得3-5个时钟;而当阵列超过L1的大小时,我将获得更高的数字(9个周期)。

2-如果我将ARRAY_SIZE增加到1,000,000以上,则会出现分段错误(内核已转储),这是由于堆栈溢出所致。 我的问题是使用动态分配( MyStruct *myS = new MyStruct[ARRAY_SIZE] )是否不会导致任何性能损失。

这是我的代码(我使用无标志的g ++编译该代码)

如果不传递-O3 ,则while ((current = current->n) != NULL)将被编译为多个内存访问,而不是单个加载指令。 通过传递-O3 ,循环将编译为:

.L3:
mov     rax, QWORD PTR [rax]
test    rax, rax
jne     .L3

正如您所期望的那样,它将在每个迭代中以4个周期运行。

请注意,可以使用__rdtsc编译器内部函数代替内联汇编。 请参阅: 获取CPU周期计数?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM