Ant*_*nio 4 java io performance solid-state-drive java-8
我有一个SSD磁盘,每个规格应提供不低于10k的IOPS.我的基准确认它可以给我20k IOPS.
然后我创建了这样一个测试:
private static final int sector = 4*1024;
private static byte[] buf = new byte[sector];
private static int duration = 10; // seconds to run
private static long[] timings = new long[50000];
public static final void main(String[] args) throws IOException {
String filename = args[0];
long size = Long.parseLong(args[1]);
RandomAccessFile raf = new RandomAccessFile(filename, "r");
Random rnd = new Random();
long start = System.currentTimeMillis();
int ios = 0;
while (System.currentTimeMillis()-start<duration*1000) {
long t1 = System.currentTimeMillis();
long pos = (long)(rnd.nextDouble()*(size>>12));
raf.seek(pos<<12);
int count = raf.read(buf);
timings[ios] = System.currentTimeMillis() - t1;
++ios;
}
System.out.println("Measured IOPS: " + ios/duration);
int totalBytes = ios*sector;
double totalSeconds = (System.currentTimeMillis()-start)/1000.0;
double speed = totalBytes/totalSeconds/1024/1024;
System.out.println(totalBytes+" bytes transferred in "+totalSeconds+" secs ("+speed+" MiB/sec)");
raf.close();
Arrays.sort(timings);
int l = timings.length;
System.out.println("The longest IO = " + timings[l-1]);
System.out.println("Median duration = " + timings[l-(ios/2)]);
System.out.println("75% duration = " + timings[l-(ios * 3 / 4)]);
System.out.println("90% duration = " + timings[l-(ios * 9 / 10)]);
System.out.println("95% duration = " + timings[l-(ios * 19 / 20)]);
System.out.println("99% duration = " + timings[l-(ios * 99 / 100)]);
}
Run Code Online (Sandbox Code Playgroud)
然后我运行这个例子并得到2186 IOPS:
$ sudo java -cp ./classes NioTest /dev/disk0 240057409536
Measured IOPS: 2186
89550848 bytes transferred in 10.0 secs (8.540234375 MiB/sec)
The longest IO = 35
Median duration = 0
75% duration = 0
90% duration = 0
95% duration = 0
99% duration = 0
Run Code Online (Sandbox Code Playgroud)
为什么它比C中的同一测试慢得多?
更新:这是Python代码,它提供20k IOPS:
def iops(dev, blocksize=4096, t=10):
fh = open(dev, 'r')
count = 0
start = time.time()
while time.time() < start+t:
count += 1
pos = random.randint(0, mediasize(dev) - blocksize) # need at least one block left
pos &= ~(blocksize-1) # sector alignment at blocksize
fh.seek(pos)
blockdata = fh.read(blocksize)
end = time.time()
t = end - start
fh.close()
Run Code Online (Sandbox Code Playgroud)
Update2:NIO代码(只是一块,不会复制所有方法)
...
RandomAccessFile raf = new RandomAccessFile(filename, "r");
InputStream in = Channels.newInputStream(raf.getChannel());
...
int count = in.read(buf);
...
Run Code Online (Sandbox Code Playgroud)
您的问题基于错误的假设,即与您的Java代码类似的C代码将与IOMeter一样好.因为这个假设是错误的,所以C性能和Java性能之间没有差异来解释.
如果你的问题是你的Java代码相对于IOMeter表现如此糟糕的原因,答案是IOMeter不会像你的代码那样一次发出一个请求.要从SSD获得完整性能,您需要保持其请求队列非空,并等待每个读取完成后再发出下一个不可能这样做.
尝试使用线程池来发出请求.