java 非缓冲与缓冲数据读取比较

时间:2023-03-09 16:34:57
java 非缓冲与缓冲数据读取比较

首先不适用缓存技术,读取数据:

//非缓冲计时
package com.swust;
import java.io.*;
/*
*功能:创建一个程序,写10000个随机双精度的数到一个文件中,同时测试运用缓冲和非缓冲技术
*
* 读取数据,求平均数,进行这种操作所需要的时间
*分析:
* 在写开始操作之前,先获取当前时间
* 再将它同操作结束后的时间作比较,以此判断各个操作的时间
*实现:
* 仍使用两个类:
*/
public class flowTest { public static void main(String[] args) { double sum=0;
try{
long start=System.currentTimeMillis();
FileInputStream fileIn = new FileInputStream("sample.ini");
DataInputStream in=new DataInputStream(fileIn);
for (int i=0;i<10000;i++){
sum+= in.readDouble();
}
in.close();
long stop=System.currentTimeMillis();
System.out.println("平均数:"+(sum/10000));
System.out.println("程序运行了:"+(stop-start));
}catch(Exception e){
System.out.println(e.toString());
} } }

运行结果:

平均数:0.5061121254198577
程序运行了:16


使用缓冲技术:

//非缓冲计时
package com.swust;
import java.io.*;
/*
*功能:创建一个程序,写10000个随机双精度的数到一个文件中,同时测试运用缓冲和非缓冲技术
*
* 读取数据,求平均数,进行这种操作所需要的时间
*分析:
* 在写开始操作之前,先获取当前时间
* 再将它同操作结束后的时间作比较,以此判断各个操作的时间
*实现:
* 仍使用两个类:
*/
public class flowTest { public static void main(String[] args) { double sum=0;
try{
long start=System.currentTimeMillis();
FileInputStream fileIn = new FileInputStream("sample.ini");
////////////////////////////////////////
BufferedInputStream bfs_in =new BufferedInputStream(fileIn);
DataInputStream in=new DataInputStream(bfs_in);
////////////////////////////////////////
for (int i=0;i<10000;i++){
sum+= in.readDouble();
}
in.close();
long stop=System.currentTimeMillis();
System.out.println("使用缓冲后\n平均数:"+(sum/10000));
System.out.println("程序运行了:"+(stop-start));
}catch(Exception e){
System.out.println(e.toString());
} } }

运行结果:

使用缓冲后
平均数:0.5061121254198577
程序运行了:0

完成这个操作几乎不到一秒的时间,这种改善非常大,读取数据的时间几乎可以忽略,所以在大数据输入的时候应该采用缓冲流