In actual development, it is found that sometimes the usage of self-developed programs is very high, which affects the normal operation of other programs on the machine. What should we do at this time?
The first thing to think of is that the best solution is to find the thread with the most CPU usage in the process (how to find the thread with the most CPU usage is not discussed here for the time being) and then optimize it. of course, there is also a limit on the Peak CPU usage of the program. when the process's usage reaches a limited peak, let him sleep (0), or waitforsingleobject. note that the CPU usage of the process mentioned here is the total CPU usage of all threads in the process. in this sense, limiting the CPU usage of a process is to limit the CPU usage of threads in the process.
So how can we get the CPU usage of the thread?
You can use the following two functions provided by the system:
Getthreadtimes and getprocesstimes. for more information about the two functions, see msdn. the last two parameters of the function return the time when the process/thread runs in kernel mode and user mode. we can get the difference between the value 2 at a certain interval and the value 2 obtained earlier, and we will get the time at which the thread/process runs on the CPU during this interval, divide the time by the interval to get the corresponding CPU usage. For example, if the running time is 10 ms and the interval is 1000 ms, the CPU usage is 1%.
If we only check the CPU usage of the thread/process, the above interval can be larger, for example, it can be more than 1 second. If we want to control its usage, it should be as small as possible, otherwise, the next monitoring time will exceed a lot of time or exceed the set peak value. but how long is this value suitable? You need to write a specific test program to test it.
The above describes how to obtain processes and threads. Sometimes the CPU usage of the entire system is required. At this time, getsystemtimes can be used. With this function, the rest of the work is the same as described above.