代碼:
---
#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統計為何差別比較大?
uj5u.com熱心網友回復:
程式比較簡單,兩個執行緒系結到不同的cpu core上,查看執行緒的cpu loading。為何task2的cpu統計差別很大uj5u.com熱心網友回復:
求解·········uj5u.com熱心網友回復:
你的程式有大量的sleepuj5u.com熱心網友回復:
為什么cpu0跑高了,cpu1上的執行緒cpu占用也高了起來?轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/123575.html
標籤:CPU和硬件區
上一篇:大佬們救急一下
下一篇:關于高并發socket
