gpt4 book ai didi

c - 为什么当我用其他任意工作使系统过载时我的程序运行得更快?

转载 作者:IT王子 更新时间:2023-10-29 00:41:08 26 4
gpt4 key购买 nike

我在运行一些计时和效率测试时遇到了一些意外行为。我发现,如果我运行其他将所有系统 CPU 核心都锁定在 100% 的后台进程,我的程序实际上运行得更快。这是一个简化的示例程序:

#define _XOPEN_SOURCE 600
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

void vadd(const float *u, const float *v, float *y, int n) {
int i;

for (i = 0; i < n; i++) {
y[i] = u[i] + v[i];
}
}

int main(int argc, char *argv[]) {
int i, its = 100000, n = 16384;
float *a, *b, *c;
clock_t start, end;
double cpu_time;

/* Make sure alignment is the same on each run. */
posix_memalign((void**)&a, 16, sizeof(float) * n);
posix_memalign((void**)&b, 16, sizeof(float) * n);
posix_memalign((void**)&c, 16, sizeof(float) * n);

/* Some arbitrary initialization */
for (i = 0; i < n; i++) {
a[i] = i;
b[i] = 4;
c[i] = 0;
}

/* Now the real work */
start = clock();
for (i = 0; i < its; i++) {
vadd(a, b, c, n);
}
end = clock();

cpu_time = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Done, cpu time: %f\n", cpu_time);

return 0;
}

我在(相当旧的)Pentium 4 @ 2.8GHz 上运行,超线程已打开,在/proc/cpuinfo 中显示为两个处理器。

系统相对空闲时的输出:

$ ./test
Done, cpu time: 11.450000

现在加载所有内核:

$ md5sum /dev/zero& ./test; killall md5sum
Done, cpu time: 8.930000

这个结果是一致的。我猜想我通过减少程序移动到另一个 CPU 的时间以某种方式提高了缓存效率,但这只是在黑暗中的一次尝试。谁能证实或反驳这一点?

第二个问题:我惊讶地发现每次运行时 cpu_time 的变化如此之大。上面使用的方法是taken right out of the GNU C manual ,并且我认为使用 clock() 可以保护我免受由于使用 CPU 的其他进程引起的时间波动的影响。显然,根据上述结果,情况并非如此。所以我的第二个问题是,clock() 方法真的是衡量性能的正确方法吗?

更新:我已经研究了有关 CPU 频率调整调节器的评论中的建议,我认为这不是这里发生的事情。我试图通过 watch grep\"cpu MHz\"/proc/cpuinfo(建议 here )实时监控 CPU 速度,但我没有看到频率变化程序正在运行。我还应该在我的帖子中说明我正在运行一个相当旧的内核:2.6.25。

更新 2: 我开始使用下面的脚本来研究启动的 md5sum 进程的数量。即使我启动的进程多于逻辑 CPU,它也比单独运行更快。

更新 3: 如果我在 BIOS 中关闭超线程,这种奇怪的行为就会消失,并且运行总是需要大约 11 秒的 CPU 时间。看起来超线程与它有关。

更新 4: 我刚刚在双四核 Intel Xeon @ 2.5GHz 上运行了这个,没有看到任何上述奇怪的行为。这个“问题”可能非常特定于我的特定硬件设置。

#!/bin/bash
declare -i num=$1

for (( num; num; num-- )); do
md5sum /dev/zero &
done

time ./test
killall md5sum

--

$ ./run_test.sh 5
Done, cpu time: 9.070000

real 0m27.738s
user 0m9.021s
sys 0m0.052s

$ ./run_test.sh 2
Done, cpu time: 9.240000

real 0m15.297s
user 0m9.169s
sys 0m0.080s

$ ./run_test.sh 0
Done, cpu time: 11.040000

real 0m11.041s
user 0m11.041s
sys 0m0.004s

最佳答案

So my secondary question is, is the clock() method really the proper way to measure performance?

您可能更喜欢使用 clock_gettime(2)和 friend 。另请阅读 time(7)

详细信息可能是硬件(即 CPU + 主板)和内核特定的。

关于c - 为什么当我用其他任意工作使系统过载时我的程序运行得更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17926038/

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