How to make the CPU usage of Windows Task Manager display a positive curve (explanation + C # implementation)

Source: Internet
Author: User

Recently, I have read a part of the thread of CLR via C #, which greatly improves the understanding of the thread. As a result, I suddenly remembered a book I saw in guanggu bookstore in college about Microsoft's interview. After several pages, I found that the author was talking about the problem. At that time, I felt that this author was very good at B, because the level of food at that time was still relatively good. Then I forgot. (Of course I didn't buy that book, but I didn't expect to apply for a job in the future)

Today, I suddenly remembered this question. After a test, it was successful. Here, I am afraid to introduce you to the principles behind the scenes and attach the Code. This kind of program has no practical significance. It is purely a kind of practice to deepen your understanding of multithreading.

Images with real images:

In fact, my first attempt was like this:

If you have any questions, read the following explanation first, and then explain the meaning of the two pictures above (first, declare that the machine is dual-core ).

1. What is the CPU usage?

First, we need to know what the CPU usage is, that is, what the data on the task manager means.

A cpu usage is the percentage of the time when the CPU actually executes commands within a period of time. For example, if your CPU runs commands within 1000 ms and 300 ms is idle, the CPU usage is 700. Therefore, we should know that the CPU usage is a statistical value of a period of time, rather than a instantaneous value at a certain time. According to the visual observation, I found that Windows Task Manager has a usage data for about one second.

Another important concept is the distinction between idle and idle CPU. CPU idling is occupied, that is, the CPU is executing some useless empty commands, just like this

1 while(true)
2 {}

The CPU continues to run at this time, which not only consumes power, but also is a waste. CPU idle means that the CPU does not execute any commands, which is generally controlled by the operating system. For example

1 Thread.Sleep(500);

It takes 500 milliseconds for the current thread to stop running. The windows scheduler suspends the thread, and the CPU is used to do other things or do nothing without power consumption. This period of time is not counted.

2. How to implement it?

Now that we know what the usage rate is, we know what to do. If we want the CPU usage to be 30% within a period of time, we need to do this:

1> execute the command at will

2> if the current consumed time does not reach 30% of the specified time, 1 is returned.

3> sleep

In this way, we can ensure that the CPU usage during this period is 30%. However, this period of time must be very small, at least less than the sampling interval of the Windows Task Manager. The smaller the value, the more accurate it is, but it is too small to control the time accurately. Therefore, the recommended time is-milliseconds.

Since we know how to control the CPU usage in a short period of time, the rest is how to generate a usage. To generate a sine usage, we need to use the math. Sin () function (nonsense ). However, the value of sin is [-0.5], and the usage is []. Therefore, we need to convert the value of sin to the usage, that is, sin (X)/2 +.

The next step is to continuously cycle from 0 to 2 * Pi, and call the CPU usage control function in the middle.

3. Problem

If you follow the above steps, it is possible to succeed, but the effect on a multi-core machine is what I first achieved (figure 2 ). The system divides a thread into two CPUs for execution, so we can only see the approximate shape. Because there are two CPUs, the maximum usage is 50%.

To solve the multi-core problem, we need to obtain the number of CPUs of the current machine, and then arrange the same number of threads to execute the loop. The most convenient is to use the queueuserworkitem of the thread pool. Then the main thread must give up the CPU and wait forever. Otherwise, your program will be shut down at once. Because the thread pool is used, you cannot set a single thread as the foreground or the background, so you can only wait for the main thread.

If multi-thread execution is set correctly, you can see the effect of 1 on your machine. The imperfection may be caused by two reasons. First, there are other programs in your system that are being executed, which will damage the existing occupation rate. Therefore, do not open other programs during testing. Another reason is that I use C #, And. NET will use the CPU during garbage collection, which will also damage the existing share. It can avoid the impact of garbage collection to some extent, but it is not worth the candle and is of little use to our program, so we can ignore it directly.

Note that in Linux, the CPU usage (top) seems to be a little different from that in windows. In Linux, each CPU is 100%, so you have two cores with a maximum share of 200%. While Windows is the sum of all cores is 100%.

4. Code
 1 using System;
2 using System.Threading;
3 using System.Diagnostics;
4
5 public sealed class Program
6 {
7 public static void Main(string[] args)
8 {
9 Console.WriteLine("Program SIN");
10 Console.WriteLine("Making the Windows Task Manager show Sine Wave Pattern in CPU usage");
11 Console.WriteLine("Now look at your task manager cpu usage!");
12
13 int numOfCPUs = Environment.ProcessorCount;
14 for(int i = 0; i < numOfCPUs; ++i)
15 {
16 ThreadPool.QueueUserWorkItem(SinWave);
17 }
18 Thread.Sleep(Timeout.Infinite);
19 }
20
21
22 private static void SinWave(object dummy)
23 {
24 while(true)
25 {
26 for(double i = 0.0; i < 2 * Math.PI; i += 0.1)
27 {
28 Compute(500, Math.Sin(i)/2.0 + 0.5);
29 }
30 }
31 }
32
33 private static Stopwatch m_sw = new Stopwatch();
34 private static void Compute(long time, double percent)
35 {
36 long runTime = (long)(time * percent);
37 long sleepTime = time - runTime;
38 m_sw.Start();
39 while(m_sw.ElapsedMilliseconds - runTime < 0 )
40 {
41 // Spin the CPU. Just doing nothing is OK
42 }
43 m_sw.Stop();
44 m_sw.Reset();
45 Thread.Sleep((int)sleepTime);
46 }
47 }

In the above Code, the compute method obtains a time parameter (time interval), and the percentage of execution time, and continuously idling the CPU to test whether the specified time has been reached, and then goes to bed. Note that the exact time is not required, because the drawing accuracy of the Windows Task Manager is also limited.

The sinewave function keeps the CPU running it at intervals of 500 milliseconds. It runs for a while and sleeps for a while, but this ratio is controlled by the sin function. The period of the sin function is controlled by the I increment in the for loop. I chose 0.1.

At last, the main function is only responsible for throwing a sinewave to the thread pool for each CPU, and then goes to bed. In this way, all CPUs can execute the same code. Then you can see the sine curve in the task manager.

5. Last two sentences

In fact, this method can implement any bounded continuous function with the limit value (Do you still remember the high number ?) . Specifically, you can map the function to [0, 1.

We strongly recommend that you read the latest version of CLR via C # (the Chinese version of the second version is enough), especially in the last part. It is very incisive to explain thread and concurrency issues, it is the essence of Richter's life, even better than Windows via C/C ++. Not necessarily C # or. NET programmers can benefit, but all programmers will. I am most familiar with C ++, but after reading CLR via C #, I have greatly improved my understanding of windows. As long as you understand it, you can do everything on your own.

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.