测试NVME的读写速率

#define _GNU_SOURCE
#include<stdio.h>
#include <time.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
//#include <unistd.h>   /* add r/w include is error */
#include <sys/time.h>

long  get_ms()
{
    
    
	struct timeval t;
	long tick;
	gettimeofday(&t, 0);
	tick = (long)(t.tv_sec) * 1000 + (long)(t.tv_usec) / 1000;
	return tick;
}

void print_usage(char* file)
{
    
    
	printf("Usage:\n");
	printf("%s   <filename>  <cnt>  <ONCE_SIZE>  <r/w>\n", file);
}

int main(int argc, char** argv)
{
    
    
	time_t Time_Start, Time_End;

	double run_time = 0;

	char* realbuff = NULL;

	int fd, i, cnt, block_size, szie;
	int pagesize, error, flags;

	if (argc != 5)
	{
    
    
		print_usage(argv[0]);
		return(-1);
	}

	if ('r' == argv[4][0])
	{
    
    
		printf("running read operations....\n");
		flags = 0;
	}
	else if ('w' == argv[4][0]) {
    
    
		printf("running write operations....\n");
		flags = 1;
	}
	else {
    
    
		printf("r/w error\n");
		return -1;
	}

	fd = open(argv[1], O_CREAT | O_RDWR | O_DIRECT);
	if (fd < 0) {
    
    
		printf("open is fail\n");
		return-1;
	}

	pagesize = getpagesize();
	cnt = strtoul(argv[2], NULL, 0);
	szie = strtoul(argv[3], NULL, 0);
	block_size = (1024 * 1024 * szie);
	realbuff = malloc(block_size + pagesize);
	if (realbuff == NULL) {
    
    
		printf("malloc realbuff is fail\n");
		return -1;
	}
	char* alignedbuff = (char*)((((unsigned int)realbuff + pagesize - 1) / pagesize) * pagesize);
	memset(alignedbuff, argv[1][1], block_size);

	if (1 == flags) {
    
    
		Time_Start = get_ms();
		for (i = 0; i < cnt; i++) {
    
    
			error = write(fd, alignedbuff, block_size);
			if (error <= 0)
			{
    
    
				perror("error:");
				printf("write is fail\n");
				free(realbuff);
				return -1;
			}
		}
		//printf("%d %s %s\n",__LINE__,__FUNCTION__,__FILE__);

		Time_End = get_ms();
		run_time = (double)(Time_End - Time_Start) / CLOCKS_PER_SEC;
		printf("write %d M cost times:%f s\n", (szie * cnt), run_time);
	}
	else {
    
    
		Time_Start = get_ms();
		for (i = 0; i < cnt; i++) {
    
    
			error = read(fd, alignedbuff, block_size);
			if (error <= 0)
			{
    
    
				perror("error:");
				printf("write is fail\n");
				free(realbuff);
				return -1;
			}
		}

		Time_End = get_ms();
		run_time = (double)(Time_End - Time_Start) / CLOCKS_PER_SEC;
		printf("read %d M cost times:%f s\n", (szie * cnt), run_time);
	}

	free(realbuff);
	close(fd);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44501989/article/details/122166778
今日推荐