/proc/self/io中的read_bytes和write_bytes是进程启动以来累计的真实磁盘I/O字节数,需两次采样求差并除以时间间隔(建议≥100ms)才能得到速率;rchar/wchar包含所有系统调用字节数(含socket、pipe等),不反映磁盘I/O;解析时须按冒号分割字段,避免使用istringstream;该文件不提供I/O等待时间,仅吞吐量统计。

Linux下用/proc/self/io读取I/O等待统计
Linux内核会为每个进程在/proc/PID/io中暴露I/O统计信息,其中rchar、wchar、read_bytes、write_bytes等字段反映实际I/O量,但注意:read_bytes和write_bytes才是真正落到存储设备的字节数,而rchar/wchar包含所有read()/write()系统调用字节数(含管道、socket等非磁盘I/O)。
要获取当前进程的I/O数据,直接打开/proc/self/io并解析对应行即可:
#include <fstream>
#include <string>
#include <unordered_map>
std::unordered_map<std::string, uint64_t> read_io_stats() {
std::ifstream f("/proc/self/io");
std::unordered_map<std::string, uint64_t> stats;
std::string line;
while (std::getline(f, line)) {
size_t pos = line.find(':');
if (pos != std::string::npos) {
std::string key = line.substr(0, pos);
std::string val = line.substr(pos + 1);
try {
stats[key] = std::stoull(val);
} catch (...) {}
}
}
return stats;
}
常见坑:
-
/proc/self/io只在Linux可用,glibc需≥2.27(旧系统可能缺失部分字段如cancelled_write_bytes) - 字段名严格区分大小写,且空格位置固定——不能用
std::istringstream简单分割,必须按冒号切分 - 该文件不反映I/O“等待时间”,只反映累计字节数;若需等待时长,得结合
/proc/self/stat里的utime/stime/cutime/cstime与delayacct(需内核开启CONFIG_TASK_DELAY_ACCT)
Windows上无法直接获取等效I/O等待统计
Windows没有与/proc/self/io对等的轻量级接口。最接近的是GetProcessIoCounters(),但它只返回ReadOperationCount、WriteOperationCount、ReadTransferCount、WriteTransferCount四组累加值,且TransferCount包含所有句柄类型(文件、pipe、socket),无法区分磁盘I/O。
立即学习“C++免费学习笔记(深入)”;
示例调用:
#include <windows.h>
#include <iostream>
void print_io_counters() {
IO_COUNTERS io;
if (GetProcessIoCounters(GetCurrentProcess(), &io)) {
std::cout << "Read bytes: " << io.ReadTransferCount << "\n"
<< "Write bytes: " << io.WriteTransferCount << "\n";
}
}
关键限制:
- 该API不提供I/O等待时间或队列延迟,仅总量统计
- 无权限时(如沙盒进程)可能返回失败,需检查
GetLastError() - 数值是进程生命周期内累计值,不支持采样差分——需自行缓存上一次值做减法
跨平台想测I/O等待?别依赖进程级统计
真正意义上的“I/O等待时间”(即线程因I/O阻塞而休眠的总时长)在用户态几乎不可靠获取。Linux下需启用delay accounting并读/proc/PID/status中的delayacct字段(需root或CAP_SYS_ADMIN),Windows则需ETW事件(如Microsoft-Windows-Kernel-IO)配合工具如tracelog.exe或PerfView。
实用建议:
- 若目标是性能分析,优先用
perf stat -e block:block_rq_issue,block:block_rq_complete(Linux)或Windows Performance Recorder(WPR)抓块层事件 - 若只是监控趋势,用
/proc/self/io或GetProcessIoCounters足够,但务必注明这是“吞吐量”,不是“等待时间” - 不要试图从
clock_gettime(CLOCK_MONOTONIC)前后打点来估算I/O等待——系统调用本身耗时、调度延迟、锁竞争都会污染结果
为什么std::cin/std::cout的I/O不体现在/proc/self/io的磁盘字段里
因为C++标准流默认使用libc缓冲,std::cin读终端或管道时,底层read()系统调用计入rchar,但不计入read_bytes(后者仅统计发往块设备的I/O)。同理,std::cout << "hello"写到tty,属于字符设备,其字节进wchar,但不出现在write_bytes中。
验证方法:
- 重定向程序输入输出到文件:
./a.out < input.txt > out.txt,此时read_bytes/write_bytes会显著增长 - 用
strace -e trace=read,write ./a.out对比系统调用字节数与/proc/self/io中rchar/wchar是否匹配 - 禁用缓冲:
std::cin.sync_with_stdio(false)不会改变这一行为——缓冲策略影响的是调用频率,不是设备类型判断
/proc/self/io,后者得动用内核追踪机制,而且通常只能全局采样,没法精确归属到单个函数调用。


















