讓CPU佔用率曲線聽你指揮—linux

來源:互聯網
上載者:User

  編程之美上的第一題,工作管理員上顯示的使用率是這樣計算的,在其重新整理周期內實際執行的指令的條數/總共可以執行的條數。總的執行條數,可以通過主頻算得,還要考慮超流水;實際執行條數就難算了。又注意到,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;
}

執行的效果:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.