两个线程,两个核,cpu统计相差大,谁能解释下?
fhvk 2019-05-13 08:03:48 代码:
---
#include <stdio.h>
#define _USE_GNU
#include <pthread.h>
#include <sys/prctl.h>
#include <stdint.h>
#include <sys/types.h>
#include <sched.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int32_t cpu1;
int32_t cpu2;
int set_cpu(int i)
{
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(i,&mask);
printf("thread %u, i = %d\n", pthread_self(), i);
if(-1 == pthread_setaffinity_np(pthread_self() ,sizeof(mask),&mask))
{
fprintf(stderr, "pthread_setaffinity_np erro\n");
return -1;
}
return 0;
}
void * task1(void *a) {
prctl(PR_SET_NAME, (char*)"task1");
set_cpu(cpu1);
uint32_t i = 1;
volatile char * src = (char *)malloc(1<<20);
volatile char * dst = (char *)malloc(1<<20);
while(1) memcpy(dst, src, 1<<20);
return NULL;
}
void * task2(void *a) {
prctl(PR_SET_NAME, (char*)"task2");
set_cpu(cpu2);
uint32_t i = 1;
volatile char *src = (char *)malloc(1<<20);
volatile char *dst = (char *)malloc(1<<20);
while(1) {usleep(10000);memcpy(dst, src, 1<<20);}
return NULL;
}
int main(int argc,char *argv[]){
pthread_t t1,t2;
printf("sample :./test 0 0\n");
if (argc != 3) {printf("input param\n");return 1;}
cpu1 = atoi(argv[1]);
if(cpu1 >= 0) {
pthread_create(&t1,NULL,task1,NULL);
usleep(1000000);
}
cpu2 = atoi(argv[2]);
if (cpu2 >= 0) {
pthread_create(&t2,NULL,task2,NULL);
}
while(1) usleep(100000);
return 0;
}
---
运行
情况1,两个线程在一个cpu core:./test 0 0
CPU0: 99.0% usr 0.9% sys 0.0% nic 0.0% idle 0.0% io 0.0% irq 0.0% sirq
CPU1: 0.9% usr 5.6% sys 0.0% nic 93.4% idle 0.0% io 0.0% irq 0.0% sirq
Load average: 1.00 0.92 0.99 2/92 3719
PID PPID USER STAT VSZ %VSZ CPU %CPU COMMAND
3717 2839 root R 24412 9.6 0 46.4 {task1} ./test 0 0
3718 2839 root S 24412 9.6 0 2.7 {task2} ./test 0 0
情况2,两个线程分别运行在两个core:./test 0 1
CPU0: 100% usr 0.0% sys 0.0% nic 0.0% idle 0.0% io 0.0% irq 0.0% sirq
CPU1: 9.2% usr 5.5% sys 0.0% nic 85.1% idle 0.0% io 0.0% irq 0.0% sirq
Load average: 1.02 0.96 1.00 2/92 3763
PID PPID USER STAT VSZ %VSZ CPU %CPU COMMAND
3761 2839 root R 24412 9.6 0 48.4 {task1} ./test 0 1
3762 2839 root S 24412 9.6 1 3.6 {task2} ./test 0 1
情况3,只运行task2线程在 core 1:./test -1 1
CPU0: 0.0% usr 0.9% sys 0.0% nic 99.0% idle 0.0% io 0.0% irq 0.0% sirq
CPU1: 4.9% usr 1.9% sys 0.0% nic 93.1% idle 0.0% io 0.0% irq 0.0% sirq
Load average: 0.92 0.97 1.00 2/97 3806
PID PPID USER STAT VSZ %VSZ CPU %CPU COMMAND
3785 2839 root S 13140 5.2 1 1.9 {task2} ./test -1 1
3786 2905 root R 3088 1.2 1 0.9 top -d 1
=========================================================
我的疑问:
3种情况下,task2的cpu统计为何差别比较大?