gpt4 book ai didi

java - 为什么 Java 磁盘 I/O 的执行速度比用 C 编写的等效 I/O 代码慢得多?

转载 作者:搜寻专家 更新时间:2023-11-01 01:16:23 24 4
gpt4 key购买 nike

我有一个 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)]);
}

然后我运行此示例并获得 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

为什么它的运行速度比用 C 编写的相同测试慢得多?

更新:这是提供 20k IOPS 的 Python 代码:

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()

Update2:NIO代码(只是一段,不会重复所有的方法)

...
RandomAccessFile raf = new RandomAccessFile(filename, "r");
InputStream in = Channels.newInputStream(raf.getChannel());
...
int count = in.read(buf);
...

最佳答案

您的问题基于错误的假设,即类似于您的 Java 代码的 C 代码的性能与 IOMeter 一样好。因为这个假设是错误的,所以 C 性能和 Java 性能之间没有差异可以解释。

如果您的问题是为什么您的 Java 代码相对于 IOMeter 执行得如此糟糕,答案是 IOMeter 不会像您的代码那样一次发出一个请求。要从您的 SSD 获得全部性能,您需要保持其请求队列非空,并且在发出下一个之前等待每个读取完成是不可能的。

尝试使用线程池来发出您的请求。

关于java - 为什么 Java 磁盘 I/O 的执行速度比用 C 编写的等效 I/O 代码慢得多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31094398/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com