According to the code list 1-5 provided in the book, you can control the CPU usage of multi-core processors.
However, when getcputickcount is used for timing, the following formula may have a small problem:
Here, according to the name defined by the millisec variable, the calculation result of the formula below is millimeter ms,
(Double) t_end-(double) t_begin)/(double) info. currentmhz
The unit of the calculated result is second.Because
_ Rdtsc () indicates the number of CPU cycles. currentmhz indicates the CPU frequency. Unit: MHz = Cycle/second = cycle * 1000/millisecond.
Therefore, if the Code defines that the CPU can work for 10 ms and the rest is 10 ms, the actual calculated time (in seconds) is 1000 different from the expected time (in MS,
The result is that the CPU usage curve in the Task Manager remains unchanged!
Code List 1-5
_ Processor_power_information Info;
Callntpowerinformation (11, // query Processor power information
Null, // no input buffer
0, // input buffer size is zero
& Info, // output buffer
Sizeof (Info); // outbuf size
_ Int64 t_begin = getcputickcount ();
// Do something
_ Int64 t_end = getcputickcount ();
Double millisec = (double) t_end-(double) t_begin)/(double) info. currentmhz;
Multi-core CPU control, CPU usage curve:
Int main ()
{
Handle curhandle = getcurrentthread (); // get the current thread handle
Dword_ptr dwthreadaffinitymask = 2;
If (! Setthreadaffinitymask (curhandle, dwthreadaffinitymask ))
{
Return 0;
}
Int busytime = 10; // 10 ms
Int idletime = busytime;
// DWORD starttime = 0;
// Obtain the number of cycles of the current CPU
Processor_power_information lpoutputbuffer;
Callntpowerinformation (
Processorinformation, // obtain the processor Information
Null,
0,
& Lpoutputbuffer,
Sizeof (lpoutputbuffer)
);
Printf ("% d", lpoutputbuffer. currentmhz );
Unsigned _ int64 starttime;
Unsigned _ int64 endtime;
While (1)
{
Starttime = _ rdtsc ();
// Note: This part should be divided by another 1000, because the number of CPU cycles is measured in MS units __rdtsc,
// Currentmhz indicates the CPU frequency. Unit: MHz = Cycle/second = cycle * 1000/millisecond
While (double) _ rdtsc ()-(double) starttime)/1000/(double) lpoutputbuffer. currentmhz) <= busytime );
Sleep (idletime );
}
Return 0;
}
# Endif