转自:http://wildwind.javaeye.com/blog/69944
前几天要写一个取得linux performance的函数。查询了一些资料。发现有几种计算cpu利用率的方法。但是都不怎么正确。最后查了以下top的源代码。现列出其计算cpu利用率的关键函数
c 代码
- typedef struct CPU_t {
- TIC_t u, n, s, i, w, x, y, z;
- TIC_t u_sav, s_sav, n_sav, i_sav, w_sav, x_sav, y_sav, z_sav;
- unsigned id;
- } CPU_t;
c 代码
- static CPU_t *cpus_refresh (CPU_t *cpus)
- {
- static FILE *fp = NULL;
- int i;
- int num;
-
- char buf[SMLBUFSIZ];
-
-
-
- if (!fp) {
- if (!(fp = fopen("/proc/stat", "r")))
- std_err(fmtmk("Failed /proc/stat open: %s", strerror(errno)));
-
-
-
- cpus = alloc_c((1 + Cpu_tot) * sizeof(CPU_t));
- }
- rewind(fp);
- fflush(fp);
-
-
- if (!fgets(buf, sizeof(buf), fp)) std_err("failed /proc/stat read");
- cpus[Cpu_tot].x = 0;
- cpus[Cpu_tot].y = 0;
- cpus[Cpu_tot].z = 0;
- num = sscanf(buf, "cpu %Lu %Lu %Lu %Lu %Lu %Lu %Lu %Lu",
- &cpus[Cpu_tot].u,
- &cpus[Cpu_tot].n,
- &cpus[Cpu_tot].s,
- &cpus[Cpu_tot].i,
- &cpus[Cpu_tot].w,
- &cpus[Cpu_tot].x,
- &cpus[Cpu_tot].y,
- &cpus[Cpu_tot].z
- );
- if (num < 4)
- std_err("failed /proc/stat read");
-
-
- if (Cpu_tot == 1) {
- cpus[1].id = 0;
- memcpy(cpus, &cpus[1], sizeof(CPU_t));
- }
-
-
- for (i = 0; 1 < Cpu_tot && i < Cpu_tot; i++) {
- if (!fgets(buf, sizeof(buf), fp)) std_err("failed /proc/stat read");
- cpus[i].x = 0;
- cpus[i].y = 0;
- cpus[i].z = 0;
- num = sscanf(buf, "cpu%u %Lu %Lu %Lu %Lu %Lu %Lu %Lu %Lu",
- &cpus[i].id,
- &cpus[i].u, &cpus[i].n, &cpus[i].s, &cpus[i].i, &cpus[i].w, &cpus[i].x, &cpus[i].y, &cpus[i].z
- );
- if (num < 4)
- std_err("failed /proc/stat read");
- }
- return cpus;
- }
c 代码
- static void summaryhlp (CPU_t *cpu, const char *pfx)
- {
-
-
- #define TRIMz(x) ((tz = (SIC_t)(x)) < 0 ? 0 : tz)
- SIC_t u_frme, s_frme, n_frme, i_frme, w_frme, x_frme, y_frme, z_frme, tot_frme, tz;
- float scale;
-
- u_frme = cpu->u - cpu->u_sav;
- s_frme = cpu->s - cpu->s_sav;
- n_frme = cpu->n - cpu->n_sav;
- i_frme = TRIMz(cpu->i - cpu->i_sav);
- w_frme = cpu->w - cpu->w_sav;
- x_frme = cpu->x - cpu->x_sav;
- y_frme = cpu->y - cpu->y_sav;
- z_frme = cpu->z - cpu->z_sav;
- tot_frme = u_frme + s_frme + n_frme + i_frme + w_frme + x_frme + y_frme + z_frme;
- if (tot_frme < 1) tot_frme = 1;
- scale = 100.0 / (float)tot_frme;
-
-
-
- show_special(
- 0,
- fmtmk(
- States_fmts,
- pfx,
- (float)u_frme * scale,
- (float)s_frme * scale,
- (float)n_frme * scale,
- (float)i_frme * scale,
- (float)w_frme * scale,
- (float)x_frme * scale,
- (float)y_frme * scale,
- (float)z_frme * scale
- )
- );
- Msg_row += 1;
-
-
- cpu->u_sav = cpu->u;
- cpu->s_sav = cpu->s;
- cpu->n_sav = cpu->n;
- cpu->i_sav = cpu->i;
- cpu->w_sav = cpu->w;
- cpu->x_sav = cpu->x;
- cpu->y_sav = cpu->y;
- cpu->z_sav = cpu->z;
-
- #undef TRIMz
- }
阅读(2112) | 评论(0) | 转发(0) |