Linux下测试SSD硬盘读写速率

硬盘分为机械硬盘HDD和固态硬盘SSD两种。现在固态硬盘已经是大势所趋咯。SSD用的接口是NVME。在NVME协议下面还有一层PCIe协议。HDD硬盘接口有SATA,SATA接口常用的工作模式有AHCI。SATA硬盘接口最大速率是600MBytes/s。接下来我通过C代码测试SSD的读写性能。


代码采用的是直接IO方式,这个测的速率不加直接IO的四倍。

test_ssd.c

#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 */

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 = clock();
	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 = clock();		
	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 = clock();
		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 = clock();	
		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;
}


代码中红色部分需要注意,不能添加这个头文件,不然会出现读写错误,可能是这个头文件下面的write和系统调用不一样。没有去追究原因。测试结果如下:



将clock()函数更改为如下:

#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;
}

                                                                                                     By Design :Linux_Google 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页