CPU-consuming Program

Source: Internet
Author: User

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:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.