Linux C Controls CPU utilization __linux

Source: Internet
Author: User
Tags usleep
1. The default frequency of the system timer in the x86 architecture is 100, that is, the clock interrupts 100 times per second on i386 processing. Therefore, a clock interrupt is generated every 10ms in the i386. 2, the process scheduling, may be the initiative to give up the CPU, or may be the clock interrupt to let the CPU. 3, control CPU utilization, is actually control CPU in totaltime time busy time busytime. The ratio of busytime and totaltime is CPU utilization. 4, there are many ways to view the CPU utilization, such as the virtual machine file system proc under the use of Cat/proc/cpuinfo. However, CPU utilization is not very clear using this approach. You can use the top command instead. To make the effect more obvious, you can set the refresh interval for the top to a smaller point. such as top-t 0.5//0.5 seconds refresh once. 5, Program design: Usleep () function can cause the process to suspend, does not occupy the CPU. Assuming that the process running on the host is smaller than the CPU, it can be assumed that the CPU is idle at this point. This allows you to control the CPU utilization of the entire Linux system by controlling how long the process is running and usleep. In order to reduce the CPU scheduling of the switching time, we make the running time for the system a clock interrupt time, that is, set total time of 100ms, running time of 10ms, idle time is 90ms. The program code is as follows: #include #include #include
#define TotalTime 100000//totaltime is 100ms = 100000us #define STARTTIME 0
void Main () {while (1) {struct Timeval tvpre, Tvafter gettimeofday (&tvpre, NULL); while (1) {Gettimeofday (& Tvafter, NULL); int interval = Tvafter.tv_usec-tvpre.tv_usec;//get the usec while (interval < 0) {interval = 1000000; The interval may be less than 0, and the interval needs to be modulo. } if (interval >= totaltime/10) break; } usleep ((totaltime*9)/10); } return; }

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.