按比例吃CPU
前几天测试软件在多核上的性能,需要按照比例吃各个CPU,查了查资料,撸了下面一小段代码;
1 #include <unistd.h> 2 #include <stdlib.h> 3 #include <stdio.h> 4 #include <time.h> 5 6 #define __USE_GNU 7 #include <pthread.h> 8 #include <sched.h> 9 10 //CPU ID号 11 #define CPU_0 0x0 12 #define CPU_1 0x01 13 #define CPU_2 0x02 14 #define CPU_3 0x03 15 16 //总时间和运行时间 17 #define FULL_TIME 100 18 #define RUN_TIME 80 19 20 //时钟HZ数 21 static clock_t clktck; 22 23 //用户参数输入的吃CPU百分比 24 static int eat_cpu_percent; 25 26 //线程绑定CPU 27 int attach_cpu(int cpu_index) 28 { 29 int cpu_num = sysconf(_SC_NPROCESSORS_CONF); 30 if (cpu_index < 0 || cpu_index >= cpu_num) 31 { 32 perror("cpu index ERROR!\n"); 33 return -1; 34 } 35 36 cpu_set_t mask; 37 CPU_ZERO(&mask); 38 CPU_SET(cpu_index, &mask); 39 40 if (pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask) < 0) 41 { 42 perror("set affinity np ERROR!\n"); 43 return -1; 44 } 45 46 return 0; 47 } 48 49 //吃CPU线程 50 void *thread_task(void *param) 51 { 52 int *cpuid = (int *)param; 53 if (attach_cpu(*cpuid) < 0) 54 { 55 pthread_exit(NULL); 56 } 57 58 clock_t time_start; 59 clock_t fulltime = FULL_TIME; 60 clock_t runtime = eat_cpu_percent; 61 while(1) 62 { 63 time_start = times(NULL); 64 while((times(NULL) - time_start) < runtime); 65 usleep((fulltime-runtime) * 1000 * 1000 / clktck); 66 } 67 68 pthread_exit(NULL); 69 } 70 71 72 int main(int argc, char *argv[]) 73 { 74 if (argc < 2) 75 { 76 printf("Please run with 0-100! Example:./eat_cpu 80\n"); 77 return -1; 78 } 79 80 eat_cpu_percent = (atoi)(argv[1]); 81 if (eat_cpu_percent < 0 || eat_cpu_percent > 100) 82 { 83 printf("eat cpu percent must in range:0-100!\n"); 84 return -1; 85 } 86 87 int ret = 0; 88 89 clktck = sysconf(_SC_CLK_TCK); 90 91 pthread_t t0; 92 int cpuid0 = CPU_0; 93 if (pthread_create(&t0, NULL, thread_task, &cpuid0) < 0) 94 { 95 perror("create thread 0 ERROR!\n"); 96 ret = -1; 97 goto _OUT; 98 } 99 100 pthread_t t1; 101 int cpuid1 = CPU_1; 102 if (pthread_create(&t1, NULL, thread_task, &cpuid1) < 0) 103 { 104 perror("create thread 1 ERROR!\n"); 105 ret = -1; 106 goto _CANCEL_0; 107 } 108 109 pthread_t t2; 110 int cpuid2 = CPU_2; 111 if (pthread_create(&t2, NULL, thread_task, &cpuid2) < 0) 112 { 113 perror("create thread 2 ERROR!\n"); 114 ret = -1; 115 goto _CANCEL_1; 116 } 117 118 pthread_t t3; 119 int cpuid3 = CPU_3; 120 if (pthread_create(&t3, NULL, thread_task, &cpuid3) < 0) 121 { 122 perror("create thread 3 ERROR!\n"); 123 ret = -1; 124 goto _CANCEL_2; 125 } 126 127 //直接停这里好了 128 while(1) 129 { 130 sleep(3600); 131 } 132 133 _CANCEL_3: 134 pthread_cancel(t3); 135 pthread_join(t3, NULL); 136 137 _CANCEL_2: 138 pthread_cancel(t2); 139 pthread_join(t2, NULL); 140 141 _CANCEL_1: 142 pthread_cancel(t1); 143 pthread_join(t1, NULL); 144 145 _CANCEL_0: 146 pthread_cancel(t0); 147 pthread_join(t0, NULL); 148 149 _OUT: 150 return ret; 151 }