消耗CPU的程序

昨天领导交代客户需要一个可以测试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
");
                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.
");
        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.
");
            return -1;
        }
    }
    
    for(i=0;i<sysconf(_SC_NPROCESSORS_CONF);i++){
        pthread_join(tid[i], NULL);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/lichmama/p/3879982.html