Yesterday, the leaders told the customer that they needed a script to test CPU performance. to simplify the problem, they wanted to create a program that could manually set CPU consumption. I thought there was such a script, maybe the performance testing tool is still similar. After thinking about it, it may be possible to use an endless loop to achieve similar results, but the impact of a single process (single thread) is limited, because the server is multiple physical cores. That is to say, I used multithreading. I manually wrote a multi-thread demo. After the demo is generated, I found that all threads work in one CPU. Although I made a single CPU 100%, but the overall consumption is not large (about 10% ). Later, Baidu said that it was useful to bind the CPU to a thread, but it was not familiar with this aspect, so the implementation of multi-process is relatively simple.
The code is simple:
#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(;;)i=(i%4)*1.0; }else{ //wait for the sub process‘s termination wait(NULL); } return 0;}
Gcc-wall test. C-O test. ochmod + X test. O # Start five sub-processes./test. O 5
Pasting: