测试read/write的读写速度案例

本文提供了一个简单的Linux读写速度测试案例,通过C语言实现,包括代码示例及运行指导。该测试通过打开指定文件,读取内容并多次写入另一文件来评估I/O性能。

前言:网上大佬们的read/write分享超级多,再结合自己的项目经验,分享一个测试read/write的读写速度案例。

大家都知道,在linux中,一切皆文件,所有的数据都是需要通过read/write进行读写的,但却不知道read/write速度到底有多快,所以今天写个分享,见识一下天下武功,唯快不破的read/write速度。

1.代码如下

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>

#define TEST_CNT          (100)
#define TEST_BUF_SIZE     (1024*1024)

static char readFile[] = "./read.file";
static char writeFile[] = "./write.file";
static unsigned char testBuf[TEST_BUF_SIZE+10];

int speedTest(void)
{
    //1.read data
    int fd_read = open(readFile, O_RDONLY);
    if (fd_read == -1)
    {
        printf("failed to open read file:%s\n", readFile);
        return 0;
    }
    int tmp = read(fd_read, testBuf, TEST_BUF_SIZE);
    printf("read %d byte.\n", tmp);
    close(fd_read);

    //2.write data and get write used time
    int fd_write = open(writeFile, O_CREAT | O_RDWR);
    if (fd_write == -1)
    {
        printf("failed to open write file:%s\n", writeFile);
        return 0;
    }

    struct timeval startTime, endTime;
    gettimeofday(&startTime, NULL);
    for(int i=0; i<TEST_CNT; ++i)
    {
        write(fd_write, testBuf, TEST_BUF_SIZE);
    }
    gettimeofday(&endTime, NULL);

    //3.calculate speed
    int writeTotalSize = TEST_BUF_SIZE * TEST_CNT;
    int writeTotalTime = (endTime.tv_sec * 1000000 + endTime.tv_usec) - (startTime.tv_sec * 1000000 + startTime.tv_usec);

    printf("writeTotalSize:%f MB, writeTotalTime:%f s, writeSpeed = %f MB/s.\n",
        (float)writeTotalSize/1024/1024, (float)writeTotalTime/1000000, ((float)writeTotalSize/1024/1024)/(writeTotalTime/1000000));

    close(fd_write);
    remove(writeFile);
    return 0;
}

int main()
{
	int ret = speedTest();
    return ret;
}

2.编译运行即可。

友情链接:

fopen()、fwrite()、fread()函数使用说明与示例_yang2011079080010的专栏-CSDN博客_fopen函数的用法

​​​​​​write函数的详解与read函数的详解_dangzhangjing97的博客-CSDN博客_write函数

Linux系统函数read()/write()/pread()/pwrite()的区别_田野-CSDN博客_pwrite

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一刀流侠客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值