背景:我们需要测量brpc
框架的通信性能,包括latency
, MBps
, qps
。
其中,latency, qps是可以查的,但是MBps需要自己算。
于是考虑读取/proc/net/dev
的相关数据进行计算。
代码如下:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
// 更改为你要监测的网卡名称,可以通过ifconfig获得
#define INTERFACE_NAME "enth0"
unsigned long long tic_bytes;
unsigned long long toc_bytes;
// 读取指定网卡的统计信息
int read_interface_stats(const char *interface_name, bool is_tic) {
FILE *file = fopen("/proc/net/dev", "r");
if (file == NULL) {
perror("Failed to open /proc/net/dev");
return -1;
}
char line[256];
while (fgets(line, sizeof(line), file)) {
if (strstr(line, interface_name) != NULL) {
if (is_tic) {
// 读取bytes的相关信息,用%*s跳过无用字符串
sscanf(line, "%*s %llu", &tic_bytes);
}
else {
sscanf(line, "%*s %llu", &toc_bytes);
}
fclose(file);
return 0;
}
}
fclose(file);
return -1;
}
int main() {
double interval = 2.0; // 采样间隔,单位为秒
while (1) {
if (read_interface_stats(INTERFACE_NAME, true) == -1) {
printf("Failed to read interface stats\n");
return 1;
}
sleep((unsigned int)interval);
if (read_interface_stats(INTERFACE_NAME, false) == -1) {
fprintf(stderr, "Failed to read interface stats\n");
return 1;
}
double bps = (toc_bytes - tic_bytes) / interval;
printf("bytes/s: %.2f\n", bps);
}
}