我有以下的任务来证明假共享,写了一个简单的程序:假共享和并行线程
#include <sys/times.h>
#include <time.h>
#include <stdio.h>
#include <pthread.h>
long long int tmsBegin1,tmsEnd1,tmsBegin2,tmsEnd2,tmsBegin3,tmsEnd3;
int array[100];
void *heavy_loop(void *param) {
int index = *((int*)param);
int i;
for (i = 0; i < 100000000; i++)
array[index]+=3;
}
int main(int argc, char *argv[]) {
int first_elem = 0;
int bad_elem = 1;
int good_elem = 32;
long long time1;
long long time2;
long long time3;
pthread_t thread_1;
pthread_t thread_2;
tmsBegin3 = clock();
heavy_loop((void*)&first_elem);
heavy_loop((void*)&bad_elem);
tmsEnd3 = clock();
tmsBegin1 = clock();
pthread_create(&thread_1, NULL, heavy_loop, (void*)&first_elem);
pthread_create(&thread_2, NULL, heavy_loop, (void*)&bad_elem);
pthread_join(thread_1, NULL);
pthread_join(thread_2, NULL);
tmsEnd1 = clock();
tmsBegin2 = clock();
pthread_create(&thread_1, NULL, heavy_loop, (void*)&first_elem);
pthread_create(&thread_2, NULL, heavy_loop, (void*)&good_elem);
pthread_join(thread_1, NULL);
pthread_join(thread_2, NULL);
tmsEnd2 = clock();
printf("%d %d %d\n", array[first_elem],array[bad_elem],array[good_elem]);
time1 = (tmsEnd1-tmsBegin1)*1000/CLOCKS_PER_SEC;
time2 = (tmsEnd2-tmsBegin2)*1000/CLOCKS_PER_SEC;
time3 = (tmsEnd3-tmsBegin3)*1000/CLOCKS_PER_SEC;
printf("%lld ms\n", time1);
printf("%lld ms\n", time2);
printf("%lld ms\n", time3);
return 0;
}
当我看到结果我感到非常惊讶(我在我的酷睿i5-430M处理器,运行它)。
- 由于虚假分享,这是1020毫秒。
- 没有虚假分享,它是710毫秒,只有30%而不是300%(它写在一些网站上,它会比300-400%更快)。
- 没有使用pthreads,它是580毫秒。
请给我看看我的错误或解释它为什么会发生。
我觉得数组[0]和阵列[1]应该在一个缓存行中。他们非常接近,不是吗? –
@AlexeyMatveev:31日和32日也非常接近。但是你认为它们属于不同的缓存行。事实是,他们可能也可能不在同一个缓存行上。如果1到5(以及1之前的所有值都适用)会进入一个缓存行,并且6个槽37会进入另一个缓存行? – 2011-11-30 19:27:34
@ Vlad-Lazarenko,我明白了,我也用另一个数字来测试它。 –