writespeed.c 2.2 KB
Newer Older
B
Bernard Xiong 已提交
1
/*
mysterywolf's avatar
mysterywolf 已提交
2
 * Copyright (c) 2006-2021, RT-Thread Development Team
B
Bernard Xiong 已提交
3
 *
M
majianjia 已提交
4
 * SPDX-License-Identifier: Apache-2.0
B
Bernard Xiong 已提交
5 6 7 8
 *
 * Change Logs:
 * Date           Author       Notes
 * 2010-02-10     Bernard      first version
M
majianjia 已提交
9
 * 2020-04-12     Jianjia Ma   add msh cmd
B
Bernard Xiong 已提交
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
 */
#include <rtthread.h>
#include <dfs_posix.h>

void writespeed(const char* filename, int total_length, int block_size)
{
    int fd, index, length;
    char *buff_ptr;
    rt_tick_t tick;

    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0);
    if (fd < 0)
    {
        rt_kprintf("open file:%s failed\n", filename);
        return;
    }

    buff_ptr = rt_malloc(block_size);
    if (buff_ptr == RT_NULL)
    {
        rt_kprintf("no memory\n");
        close(fd);
        return;
    }

D
David Lin 已提交
35 36 37 38 39 40
    /* prepare write data */
    for (index = 0; index < block_size; index++)
    {
        buff_ptr[index] = index;
    }
    index = 0;
B
Bernard Xiong 已提交
41

D
David Lin 已提交
42
    /* get the beginning tick */
B
Bernard Xiong 已提交
43
    tick = rt_tick_get();
D
David Lin 已提交
44 45 46 47 48 49 50 51
    while (index < total_length / block_size)
    {
        length = write(fd, buff_ptr, block_size);
        if (length != block_size)
        {
            rt_kprintf("write failed\n");
            break;
        }
B
Bernard Xiong 已提交
52

D
David Lin 已提交
53 54
        index ++;
    }
B
Bernard Xiong 已提交
55 56
    tick = rt_tick_get() - tick;

D
David Lin 已提交
57
    /* close file and release memory */
B
Bernard Xiong 已提交
58
    close(fd);
D
David Lin 已提交
59
    rt_free(buff_ptr);
B
Bernard Xiong 已提交
60 61 62 63 64 65 66 67

    /* calculate write speed */
    rt_kprintf("File write speed: %d byte/s\n", total_length / tick * RT_TICK_PER_SECOND);
}

#ifdef RT_USING_FINSH
#include <finsh.h>
FINSH_FUNCTION_EXPORT(writespeed, perform file write test);
M
majianjia 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94

static void cmd_writespeed(int argc, char *argv[])
{
    char* filename;
    int length;
    int block_size;

    if(argc == 4)
    {
        filename = argv[1];
        length = atoi(argv[2]);
        block_size = atoi(argv[3]);
    }
    else if(argc == 2)
    {
        filename = argv[1];
        block_size = 512;
        length = 1024*1024;
    }
    else
    {
       rt_kprintf("Usage:\nwritespeed [file_path] [length] [block_size]\n");
       rt_kprintf("writespeed [file_path] with default length 1MB and block size 512\n");
       return;
    }
    writespeed(filename, length, block_size);
}
95
MSH_CMD_EXPORT_ALIAS(cmd_writespeed, writespeed, test file system write speed);
M
majianjia 已提交
96
#endif /* RT_USING_FINSH */