IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    随想编程:写1G的随机整数到硬盘的时长

    longhao (longtask@gmail.com)发表于 2010-08-12 06:22:02
    love 0

        产品部的小朋友告诉我,他写1G的随机数到硬盘,竟然回full gc,那肯定是代码中产生的对象没有回收。该小朋友写1G内容到硬盘需要的市场是95秒左右,很明显效率很低。还是整理一下需求吧!

        目标:最快的速度向硬盘写1G的随机数。

        注意事项:

        1:申请的空间不要大于新生代的大小(jdk通过-Xmn来设置);

        2:每次对象写到硬盘后,注意清理对象;

        我写的一个版本:(我测试的最快速度在15.396秒)

    public class WriteFile {
        public static void main(String[] args) throws Exception{
            long start = System.currentTimeMillis();
            WriteFile.generateFile(1024 * 1024 * 1024);
            long end = System.currentTimeMillis();
            System.out.println(end - start);
        }
        public static void generateFile(int size) throws Exception{
            RandomAccessFile raf = new RandomAccessFile("d:/random","rw");
            FileChannel channel = raf.getChannel();
            int count = size/allocateSize;
            long start = System.currentTimeMillis();
            ByteBuffer buffer = ByteBuffer.allocate(allocateSize);
            long end = System.currentTimeMillis();
            System.out.println(end - start);
            for(int i=0;i<count;i++){
                long aa = System.currentTimeMillis();
                for(int j=0;j<allocateSize/4;j++){
                                int num= random.nextInt(100000000);
                                buffer.putInt(num);
                }
                buffer.flip();
                channel.write(buffer);
                long xx = System.currentTimeMillis();
                System.out.println(xx - aa);
                buffer.clear();//别忘了clear
            }
            channel.close();
            raf.close();
        }
        private static Random random = new Random();
        //需要申请的空间,大小不要查过-xmn
        private static final int allocateSize = 30 * 1024 * 1024;
    }

        需要思考的问题:

        1:一边生成一边写如何?这是不是要考虑生产者消费者模式?

        2:如果申请的空间大小超过-xmn设置的值,会报什么错?

        3:如何对这个文件中的整数排序?(应该有重复的数字)

        4:有没有更快的方法写随机数到硬盘?



沪ICP备19023445号-2号
友情链接