gpt4 book ai didi

c++ - 为什么不同的 cpu 对执行相同的代码需要不同的时间

转载 作者:搜寻专家 更新时间:2023-10-31 01:24:21 24 4
gpt4 key购买 nike

我创建了一个程序,它从 argv 中获取参数并为每个参数创建一个线程,并将线程关联设置为参数的 int 值。例如./main 3 4将创建两个线程,第一个线程将在第三个 CPU 上运行,第二个线程将使用第四个 CPU。

一个线程需要一秒钟才能完成(对数组 int[10000] 进行数学运算)当我运行 time ./main 1 2 时,我看到了预期的 1 秒实时但是当我运行 time ./main 1 3 时,我看到了 2 秒而不是 1 秒我认为这与 numa 节点有关,但是time ./main 1 4 结果为 1 秒实时

经过更多测试后,我发现只有 1 3 和 2 4 对花费的时间是预期的两倍。用户时间也是两倍。

$ time ./main 1 2
real 0m1.058s
user 0m2.100s

$ time ./main 1 3
real 0m2.019s
user 0m4.016s

$ time ./main 1 4
real 0m1.090s
user 0m2.152s

$ time ./main 2 4
real 0m2.014s
user 0m4.016s

$ time ./main 2 3
real 0m1.094s
user 0m2.156s

$ time ./main 3 4
real 0m1.170s
user 0m2.316s

我正在测试的代码。我跳过了 set_affinity 函数

void math_ops() {
size_t len = 14800; // with this number it takes around 1s to compute on my hardware
int* abc = new int[len+1];
memset(abc, 7, len);
for(int i = 1; i < len; i++) {
for(int j = 1; j < len; j++) {
abc[i] *= abc[j];
abc[j+1] -= abc[i-1];
abc[j-1] -= abc[i+1];
}
}
}

int main(int argc, char** argv) {
std::vector<std::thread> vec(argc);
int thread_num = argc - 1;
for (int i = 0; i < thread_num; i++) {
std::thread t(math_ops);
// sets thread affinity equal to the second parameter
set_affinity(t, atoi(argv[i+1]) - 1);
vec[i] = std::move(t);
}
for (int i = 0; i < thread_num; i++) {
vec[i].join();
}
return 0;
}

有谁知道为什么 cpu 对 1,3 和 2,4 的执行时间是原来的两倍?

最佳答案

这可能是由于 hyperthreading .您看到的四个核心并不是真正的 4 个核心,它们可能只是两个核心,具有两倍的执行单元。这意味着在属于同一物理内核的虚拟内核上运行的两个线程必须共享该内核的部分资源。

当您在两个不同的物理内核上运行时,没有资源共享,代码执行速度更快。

您可以通过阅读 /sys/devices/system/cpu/cpu0/topology/thread_siblings_list 找出哪些内核是兄弟内核(将 cpu0 替换为任何其他内核#)

关于c++ - 为什么不同的 cpu 对执行相同的代码需要不同的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58221775/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com