[英]How to get CPU usage in C program with percentage %
我嘗試使用 c 程序獲取 CPU 使用率,但結果沒有以百分比顯示,這段代碼有什么問題? 也許有人可以澄清或提供另一種方法來恢復使用的 CPU。
我的代碼:
int GetCPULoad() {
int FileHandler;
char FileBuffer[1024];
float load;
FileHandler = open("/proc/loadavg", O_RDONLY);
if(FileHandler < 0) {
return -1; }
read(FileHandler, FileBuffer, sizeof(FileBuffer) - 1);
sscanf(FileBuffer, "%f", &load);
close(FileHandler);
return (int)(load * 100);
}
也許我可以用 /proc/stat 文件做到這一點,有人知道該怎么做嗎?
我嘗試了另一個代碼
fp = fopen ("/proc/stat", "r");
if (fp) {
long long unsigned int user,nice,system,idle;
int i = fscanf(fp,"%*s %llu %llu %llu %llu",&user,&nice,&system,&idle);
int total_cpu_usage1;
total_cpu_usage1 = user + nice + system + idle;
sprintf( http_buf,"<br>CPU usage: %d ", total_cpu_usage1); tcp_write(&tcpbuf, sock, http_buf, strlen(http_buf) );
fclose(fp);
}
但結果相同:CPU 使用率:159838295
我怎樣才能得到百分比?
最簡單的方法是使用具有不同范圍和不同增量的多個循環。
for (i = 1; i < 10; i++) {
...
}
for (i = 10; i <= 30; i += 10) {
...
}
for (i = 60; i <= 120; i += 30) {
...
}
如果您真的必須在一個循環中執行此操作:
for (i = 1; i <= 120;
i = i < 10 ? i + 1 :
(i < 30 ? i + 10 : i + 30))
for
循環的最后一部分 header 將i
增加不同的值,具體取決於它所在的范圍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.