In the beauty of programming, the usage shown on the task manager is calculated in this way. The number of commands actually executed/The total number of executable commands within the refresh cycle. The total number of execution items can be calculated by the clock speed, and the overrunning state must be considered. It is difficult to calculate the actual number of execution items. Note that the CPU performs operations at full speed, so the CPU can be executed at full speed within a short period of time, and nothing can be done in a short period of time.
In addition, multi-core CPU switches between CPUs. However, all operating systems have system calls that set the CPU affinity of processes.Sched_setaffinity.
The followingProgramIt can run on a dual-core or above computer, and you will see a CPU draw a straight line, and the other painting a sin curve. Great!
# Include < Stdio. h >
# Include < Math. h >
# Include < Unistd. h >
# Include < Sys / Times. h >
# Define _ Use_gnu
# Include < Sched. h >
// Set the CPU on which the process runs
Void Set_cpu ( Int ID)
{
Cpu_set_t mask;
Cpu_zero ( & Mask );
Cpu_set (ID, & Mask );
If (Sched_setaffinity ( 0 , Sizeof (Mask ), & Mask) = - 1 ){
Fprintf (stderr, " Warning: cocould not set CPU affinity \ n " );
}
}
Clock_t Hz; // Clock Interruption Frequency
Void Draw_line ( Int Cpu_id)
{
Set_cpu (cpu_id );
Clock_t busy = Hz / 50 ; // 20 ms
Clock_t idle = Busy;
Clock_t start;
While ( 1 ){
Start = Times (null );
// Busy Loop
While (Times (null) - Start <= Busy)
;
// Idle Loop
Usleep (idle * 1000 * 1000 / Hz );
}
}
# Define Count 1, 200 // Divided into 200 Residential Areas
Void Draw_sin ( Int Cpu_id)
{
Set_cpu (cpu_id );
Int I;
Const Double Pi = 3.1415926 ;
Const Clock_t Interval = Hz * 2 ;
Clock_t busy_span [count];
Clock_t idle_span [count];
Clock_t half = Interval / 2 ;
Double Radian = 0.0 ;
For (I = 0 ; I < Count; ++ I ){ // Pre-Calculation
Busy_span [I] = Half * ( 1 + Sin (Pi * Radian ));
Idle_span [I] = Interval - Busy_span [I];
Radian + = ( 2 / Count );
}
Clock_t start;
For (I = 0 ; 1 ; ++ I ){
I % = Count;
Start = Times (null );
While (Times (null) - Start <= Busy_span [I])
;
Usleep (idle_span [I] * 1000 * 1000 / Hz );
}
}
Int Main ()
{
Hz = Sysconf (_ SC _clk_tck );
Pid_t PID;
PID = Fork ();
If (PID = 0 ){
Draw_line ( 0 );
} Else {
Draw_sin ( 1 );
}
Return 0 ;
}
Execution result: