Linux磁盘测速2 - 代码测速
承接上一篇 win和linux下的磁盘测速(读写速度) 命令行工具测速
测试主程序
主要就是从磁盘特定位置读文件,输出读文件时间和速度。(如果没有大文件,请看下一节,自己生成随机数据集)
// run with
// g++ -o exec_disk_speed_test disk_speed_test.cpp
// ./exec_disk_speed_test
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <iostream>
#include <stdint.h>
int main() {
std::string path = "/data/WEB/02.tar";
FILE *file = fopen(path.c_str(), "rb");
if (!file) {
std::cout << "can not open file" << std::endl;
return 0;
}
// int i = 0;
struct stat statBuffer;
stat(path.c_str(), &statBuffer);
uint64_t length = statBuffer.st_size;
printf("FileSize : %lu\n", length);
uint8_t *buffer = (uint8_t *)malloc(length);
uint64_t readOffset = 0;
uint64_t readOnce = 0;
uint64_t onceLength = 16 * 1024 * 1024;
struct timeval t0, t1;
gettimeofday(&t0, 0);
while (readOnce = fread(buffer + readOffset, 1, onceLength, file)) {
readOffset += readOnce;
}
gettimeofday(&t1, 0);
fclose(file);
uint64_t times = (t1.tv_sec - t0.tv_sec) * 1000000 + t1.tv_usec - t0.tv_usec;
printf("readSize : %f MB\n", (float)readOffset / 1024 / 1024);
printf("timecost : %f s\n", (float)times / 1000000);
printf("throuput : %lf MB/s\n",
(double)readOffset * 1000000 / 1024 / 1024 / times);
return 0;
}
以上代码保存成disk_speed_test.cpp,命令行编译和运行:
g++ -o exec_disk_speed_test disk_speed_test.cpp
./exec_disk_speed_test
生成随机文件
如果没有大文件,可以考虑使用如下程序生成:
1 #include <stdio.h>
2 #include <time.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #define FILE_SIZE 1024 * 10
6 int main(void)
7 {
8 u_int16_t randm;
9 srand((unsigned)time(NULL));
10 FILE *randomFile = fopen("random_data_10GB", "w");
11 for (int j = 0; j < FILE_SIZE; j++)
12 {
13 for (int i = 0; i < 1024 * 512; i++)
14 {
15 randm = rand() & 0xffff;
16 fwrite(&randm, 2, 1, randomFile);
17 }
18 }
19
20 fclose(randomFile);
21 }
保存成gen_data.c,使用如下命令编译运行
gcc -o exec_gen_data gen_data.c
./exec_gen_data
备注(两次测速之间需要清除缓存)
两次测速之间需要清除缓存,使用如下命令(需要等待大概5s运行完成):
sudo sh -c 'sync && echo 3 > /proc/sys/vm/drop_caches'
如果不清除缓存,那么很可能会发生,越读越快的情况。
两次运行之间不清除缓存
wc@r740:~/EDCR/disk_speed_test$ ./exec
FileSize : 2648698880
readSize : 2525.996094 MB
timecost : 8.629814 s
throuput : 292.705740 MB/s
wc@r740:~/EDCR/disk_speed_test$ ./exec
FileSize : 2648698880
readSize : 2525.996094 MB
timecost : 1.822220 s
throuput : 1386.219059 MB/s
wc@r740:~/EDCR/disk_speed_test$
两次运行之间清除缓存
wc@r740:~/EDCR/disk_speed_test$ ./exec
FileSize : 2648698880
readSize : 2525.996094 MB
timecost : 8.683556 s
throuput : 290.894202 MB/s
wc@r740:~/EDCR/disk_speed_test$ sudo sh -c 'sync && echo 3 > /proc/sys/vm/drop_caches'
wc@r740:~/EDCR/disk_speed_test$ ./exec
FileSize : 2648698880
readSize : 2525.996094 MB
timecost : 8.662859 s
throuput : 291.589196 MB/s