按比例吃CPU
阅读原文时间:2023年07月16日阅读:2

前几天测试软件在多核上的性能,需要按照比例吃各个CPU,查了查资料,撸了下面一小段代码;

#include
#include
#include
#include

#define __USE_GNU
#include
#include

//CPU ID号
#define CPU_0 0x0
#define CPU_1 0x01
#define CPU_2 0x02
#define CPU_3 0x03

//总时间和运行时间
#define FULL_TIME 100
#define RUN_TIME 80

//时钟HZ数
static clock_t clktck;

//用户参数输入的吃CPU百分比
static int eat_cpu_percent;

//线程绑定CPU
int attach_cpu(int cpu_index)
{
int cpu_num = sysconf(_SC_NPROCESSORS_CONF);
if (cpu_index < || cpu_index >= cpu_num)
{
perror("cpu index ERROR!\n");
return -;
}

 cpu\_set\_t mask;  
 CPU\_ZERO(&mask);  
 CPU\_SET(cpu\_index, &mask);

 if (pthread\_setaffinity\_np(pthread\_self(), sizeof(mask), &mask) < )  
 {  
     perror("set affinity np ERROR!\\n");  
     return -;  
 }

 return ;  

}

//吃CPU线程
void *thread_task(void *param)
{
int *cpuid = (int *)param;
if (attach_cpu(*cpuid) < )
{
pthread_exit(NULL);
}

 clock\_t time\_start;  
 clock\_t fulltime = FULL\_TIME;  
 clock\_t runtime = eat\_cpu\_percent;  
 while()  
 {  
     time\_start = times(NULL);  
     while((times(NULL) - time\_start) < runtime);  
     usleep((fulltime-runtime) \*  \*  / clktck);  
 }

 pthread\_exit(NULL);  

}

int main(int argc, char *argv[])
{
if (argc < )
{
printf("Please run with 0-100! Example:./eat_cpu 80\n");
return -;
}

 eat\_cpu\_percent = (atoi)(argv\[\]);  
 if (eat\_cpu\_percent <  || eat\_cpu\_percent > )  
 {  
     printf("eat cpu percent must in range:0-100!\\n");  
     return -;  
 }

 int ret = ;

 clktck = sysconf(\_SC\_CLK\_TCK);

 pthread\_t t0;  
 int cpuid0 = CPU\_0;  
 if (pthread\_create(&t0, NULL, thread\_task, &cpuid0) < )  
 {  
     perror("create thread 0 ERROR!\\n");  
     ret = -;  
     goto \_OUT;  
 }

 pthread\_t t1;  
 int cpuid1 = CPU\_1;  
 if (pthread\_create(&t1, NULL, thread\_task, &cpuid1) < )  
 {  
     perror("create thread 1 ERROR!\\n");  
     ret = -;  
     goto \_CANCEL\_0;  
 }

 pthread\_t t2;  
 int cpuid2 = CPU\_2;  
 if (pthread\_create(&t2, NULL, thread\_task, &cpuid2) < )  
 {  
     perror("create thread 2 ERROR!\\n");  
     ret = -;  
     goto \_CANCEL\_1;  
 }

 pthread\_t t3;  
 int cpuid3 = CPU\_3;  
 if (pthread\_create(&t3, NULL, thread\_task, &cpuid3) < )  
 {  
     perror("create thread 3 ERROR!\\n");  
     ret = -;  
     goto \_CANCEL\_2;  
 }

 //直接停这里好了  
 while()  
 {  
     sleep();  
 }

_CANCEL_3:
pthread_cancel(t3);
pthread_join(t3, NULL);

_CANCEL_2:
pthread_cancel(t2);
pthread_join(t2, NULL);

_CANCEL_1:
pthread_cancel(t1);
pthread_join(t1, NULL);

_CANCEL_0:
pthread_cancel(t0);
pthread_join(t0, NULL);

_OUT:
return ret;
}