昨天領導交代客戶需要一個可以測試CPU性能的腳本,問題簡化下就是說要做一個可以手動設置對CPU產生消耗的程序。心想哪有這種腳本,或許性能測試工具還差不多。琢磨了下,或許用死循環可以達到差不多的效果,但是單進程(單線程)造成的影響有限,因為服務器都是多個物理核心。那就是用多線程吧,手動寫了個多線程demo,生成后發現線程都集中在一個CPU內工作,雖然把單個CPU搞成100%了,但是整體消耗不大(大約10%左右)。后來百度了下說得CPU綁定線程才有用,但是這方面不是一下就能熟悉的,所以還是多進程的實現較為簡單。
代碼很簡單:
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <wait.h> /** *@Usage: ./$0 [SUBPROCESS NUMBER] */ int main(int argc, char *argv[]){ pid_t pid; int i, pn=4; if(argc==2){ pn=atoi(argv[1]); } for(i=0;i<pn;i++){ pid=fork(); if(pid<=0)break; } if(pid<0){ printf("fork() error\n"); return -1; }else if(pid==0){ //sub process works for(;;); }else{ //wait for the sub process's termination wait(NULL); } return 0; }
gcc -Wall test.c -o test.o chmod +x test.o #啟動五個子進程試試效果 ./test.o 5
貼張圖:
多線程的實現代碼:
/** *參考鏈接 *@http://blog.csdn.net/dodng12/article/details/8840271 *@http://fanqiang.chinaunix.net/a4/b8/20010811/0905001105.html *@http://www.ibm.com/developerworks/cn/linux/l-cn-mthreadps/ */ #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include <sched.h> void *thread(void *arg){ cpu_set_t cst; int cpu=*((int *)arg); CPU_ZERO(&cst); CPU_SET(cpu, &cst); if(pthread_setaffinity_np(pthread_self(), sizeof(cst), &cst)!=0){ printf("set thread affinity failed.\n"); pthread_exit(NULL); } for(;;); } //gcc -Wall -lpthread thread.c -o thread.o int main(void){ int i; pthread_t tid[256]; int cpus[256]; for(i=0;i<sysconf(_SC_NPROCESSORS_CONF);i++){ //線程參數不能用公用變量傳遞,要確保每個參數值的地址都是被獨立使用的 cpus[i]=i; if(pthread_create(&tid[i], NULL, thread, (void *)(&cpus[i]))!=0){ printf("create thread failed.\n"); return -1; } } for(i=0;i<sysconf(_SC_NPROCESSORS_CONF);i++){ pthread_join(tid[i], NULL); } return 0; }