我在Linux中在一个带有1个套接字,4个内核的服务器上做了一个sched_setaffinity测试,下面的/ proc/cpuinfo显示了cpu信息:
processor : 0
model name : Intel(R) Core(TM)2 Quad CPU Q8400 @ 2.66GHz
cache size : 2048 KB
physical id : 0
siblings : 4
cpu cores : 4
processor : 1
model name : Intel(R) Core(TM)2 Quad CPU Q8400 @ 2.66GHz
cache size : 2048 KB
physical id : 0
siblings : 4
cpu cores : 4
processor : 2
model name : Intel(R) Core(TM)2 Quad CPU Q8400 @ 2.66GHz
cache size : 2048 KB
physical id : 0
siblings : 4
cpu cores : 4
processor : 3
model name : Intel(R) Core(TM)2 Quad CPU Q8400 @ 2.66GHz
cache size : 2048 KB
physical id : 0
siblings : 4
cpu cores : 4
Run Code Online (Sandbox Code Playgroud)
我有一个简单的测试应用程序:
struct foo {
int x;
int y;
} ;
//globar var
volatile struct foo fvar ;
pid_t gettid( void )
{
return syscall( __NR_gettid );
}
void *test_func0(void *arg)
{
int proc_num = (int)(long)arg;
cpu_set_t set;
CPU_ZERO( &set );
CPU_SET( proc_num, &set );
printf("proc_num=(%d)\n",proc_num) ;
if (sched_setaffinity( gettid(), sizeof( cpu_set_t ), &set ))
{
perror( "sched_setaffinity" );
return NULL;
}
int i=0;
for(i=0;i<1000000000;++i){
__sync_fetch_and_add(&fvar.x,1);
}
return NULL;
} //test_func0
Run Code Online (Sandbox Code Playgroud)
编译:gcc testsync.c -D_GNU_SOURCE -lpthread -o testsync.exe以下是测试结果:
2 threads running test_func0 in core 0,1 take 35 secs ;
2 threads running test_func0 in core 0,2 take 55 secs ;
2 threads running test_func0 in core 0,3 take 55 secs ;
2 threads running test_func0 in core 1,2 take 55 secs ;
2 threads running test_func0 in core 1,3 take 55 secs ;
2 threads running test_func0 in core 2,3 take 35 secs ;
Run Code Online (Sandbox Code Playgroud)
我想知道为什么在核心(0,1)或核心(2,3)中运行的2个线程在其他线程中会更快?如果我在同一个核心运行2个线程,比如核心(1,1),核心(2,2),核心(3,3),这将花费28秒,也会混淆为什么会发生这种情况?
核心0和1共享L2缓存,核心2和3也共享.在共享缓存的两个核心上运行使共享变量保留在L2缓存中,这使事情变得更快.
在今天的英特尔处理器中并非如此,其中L2是每核心.但是在你正在使用的CPU上,这是它的工作原理(它实际上是通过将两个双核CPU粘合在一起而制成的四核CPU).