編程之美上的第一題,工作管理員上顯示的使用率是這樣計算的,在其重新整理周期內實際執行的指令的條數/總共可以執行的條數。總的執行條數,可以通過主頻算得,還要考慮超流水;實際執行條數就難算了。又注意到,CPU在執行運算時是全速進行的,所以可以讓CPU在一小段時間內全速執行,一小段時間裡什麼也不幹。
另外,多核CPU會發生進程在CPU之間的切換,不過各種作業系統都有設定進程CPU親和度的系統調用,linux系統是sched_setaffinity。
下面這個程式可以運行在雙核以上電腦上,你會看到一個CPU在畫直線,另一個在畫sin曲線。很好玩吧!
#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <sys/times.h>
#define __USE_GNU
#include <sched.h>
// 設定進程在哪個cpu上運行
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: could not set CPU affinity\n");
}
}
clock_t Hz; // 時鐘中斷頻率
void draw_line(int cpu_id)
{
set_cpu(cpu_id);
clock_t busy = Hz / 50; // 20ms
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 200 // 分成200個小區間
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) { // 預計算
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;
}
執行的效果: