繁体   English   中英

Java-为什么二进制堆的实现比其他方法快?

[英]Java - Why is this implementation of a binary heap faster than the other?

在阅读了一些有关堆/优先级队列的知识之后,我最近做了一个自己的实现。 之后,我决定将实现的性能与我在书中找到的实现的性能进行比较,结果令我有些困惑。 看来,两种实现的插入方法之间存在巨大的性能差异。

我使用此代码测试了两个堆:

Random rnd = new Random();
long startTime = System.currentTimeMillis();
for(int i = 0; i < 1_000_000_0; i++) heap.insert(rnd.nextInt(1000));
System.out.println(System.currentTimeMillis() - startTime);

当我用我的堆实现运行它时,我得到大约600ms的结果。 当我用本书的实现来运行它时,我得到了大约1900ms的时间。 差异怎么可能这么大? 当然,我的实现肯定有问题。

我的实现:

public class Heap<T extends Comparable<? super T>> {

    private T[] array = (T[])new Comparable[10];
    private int size = 0;

    public void insert(T data) {
        if(size+1 > array.length) expandArray();

        array[size++] = data;
        int pos = size-1;
        T temp;

        while(pos != 0 && array[pos].compareTo(array[pos/2]) < 0) {
            temp = array[pos/2];
            array[pos/2] = array[pos];
            array[pos] = temp;
            pos /= 2;
        }
    }

    private void expandArray() {
        T[] newArray = (T[])new Comparable[array.length*2];

        for(int i = 0; i < array.length; i++)
            newArray[i] = array[i];

        array = newArray;
    }
}

本书的实现:

public class BooksHeap<AnyType extends Comparable<? super AnyType>>
{
    private static final int DEFAULT_CAPACITY = 10;

    private int currentSize;
    private AnyType [ ] array;

    public BinaryHeap( )
    {
        this( DEFAULT_CAPACITY );
    }

    public BinaryHeap( int capacity )
    {
        currentSize = 0;
        array = (AnyType[]) new Comparable[ capacity + 1 ];
    }

    public void insert( AnyType x )
    {
        if( currentSize == array.length - 1 )
            enlargeArray( array.length * 2 + 1 );

        int hole = ++currentSize;
        for( array[ 0 ] = x; x.compareTo( array[ hole / 2 ] ) < 0; hole /= 2 )
            array[ hole ] = array[ hole / 2 ];
        array[ hole ] = x;
    }


    private void enlargeArray( int newSize )
    {
            AnyType [] old = array;
            array = (AnyType []) new Comparable[ newSize ];
            for( int i = 0; i < old.length; i++ )
                array[ i ] = old[ i ];        
    }
}

编辑:这本书是Mark Allen Weiss撰写的“ Java中的数据结构和算法分析”。 第三版。 书号:0-273-75211-1。

在这里,您的代码使用JMH进行了度量:

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@OperationsPerInvocation(Measure.SIZE)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Thread)
@Fork(1)
public class Measure
{
  static final int SIZE = 4_000_000;
  private Random rnd;

  @Setup public void setup() {
    rnd  = new Random();
  }

  @Benchmark public Object heap() {
    Heap<Integer> heap = new Heap<>();
    for (int i = 0; i < SIZE; i++) heap.insert(rnd.nextInt());
    return heap;
  }

  @Benchmark public Object booksHeap() {
    BooksHeap<Integer> heap = new BooksHeap<>();
    for (int i = 0; i < SIZE; i++) heap.insert(rnd.nextInt());
    return heap;
  }

  public static class Heap<T extends Comparable<? super T>> {

    private T[] array = (T[])new Comparable[10];
    private int size = 0;

    public void insert(T data) {
      if(size+1 > array.length) expandArray();

      array[size++] = data;
      int pos = size-1;
      T temp;

      while(pos != 0 && array[pos].compareTo(array[pos/2]) < 0) {
        temp = array[pos/2];
        array[pos/2] = array[pos];
        array[pos] = temp;
        pos /= 2;
      }
    }

    private void expandArray() {
      T[] newArray = (T[])new Comparable[array.length*2];
      for (int i = 0; i < array.length; i++)
        newArray[i] = array[i];
      array = newArray;
    }
  }

  public static class BooksHeap<AnyType extends Comparable<? super AnyType>>
  {
    private static final int DEFAULT_CAPACITY = 10;

    private int currentSize;
    private AnyType [ ] array;

    public BooksHeap()
    {
      this( DEFAULT_CAPACITY );
    }

    public BooksHeap( int capacity )
    {
      currentSize = 0;
      array = (AnyType[]) new Comparable[ capacity + 1 ];
    }

    public void insert( AnyType x )
    {
      if( currentSize == array.length - 1 )
        enlargeArray( array.length * 2 + 1 );

      int hole = ++currentSize;
      for( array[ 0 ] = x; x.compareTo( array[ hole / 2 ] ) < 0; hole /= 2 )
        array[ hole ] = array[ hole / 2 ];
      array[ hole ] = x;
    }


    private void enlargeArray( int newSize )
    {
      AnyType [] old = array;
      array = (AnyType []) new Comparable[ newSize ];
      for( int i = 0; i < old.length; i++ )
        array[ i ] = old[ i ];
    }
  }
}

结果:

Benchmark          Mode  Cnt   Score    Error  Units
Measure.booksHeap  avgt    5  62,712 ± 23,633  ns/op
Measure.heap       avgt    5  62,784 ± 44,228  ns/op

他们是完全一样的。

练习的寓意:不要以为您可以编写一个循环并将其称为基准 在复杂的,自我优化的运行时(例如HotSpot)中测量任何有意义的事情都是一项极其艰巨的挑战,最好由像JMH这样的专家基准测试工具来完成。

附带说明一下,如果您使用System.arraycopy而不是手动循环,则可以在两种实现中节省20%的时间。 令人尴尬的是,这不是我的主意-IntelliJ IDEA的自动检查建议这样做,并自行转换代码:)

考虑到该问题的实现测试,如何测试这些实现可以解释很多不同之处,请考虑以下示例。 当我将您的OPHeap在名为OPHeap的类中,而书的BookHeap在名为BookHeap的类中,然后按此顺序进行测试时:

import java.util.Random;

public class Test {
    public static void main(String ...args) {
        {
            Random rnd = new Random();
            BookHeap<Integer> heap = new BookHeap<Integer>();
            long startTime = System.currentTimeMillis();
            for(int i = 0; i < 1_000_000_0; i++) heap.insert(rnd.nextInt(1000));
            System.out.println("Book's Heap:" + (System.currentTimeMillis() - startTime));
        }
        {
            Random rnd = new Random();
            OPHeap<Integer> heap = new OPHeap<Integer>();
            long startTime = System.currentTimeMillis();
            for(int i = 0; i < 1_000_000_0; i++) heap.insert(rnd.nextInt(1000));
            System.out.println("  OP's Heap:" + (System.currentTimeMillis() - startTime));
        }
    }
}

我得到以下输出:

Book's Heap:1924
  OP's Heap:1171

但是,当我交换测试顺序时,会得到以下输出:

  OP's Heap:1867
Book's Heap:1515

这就是所谓的“热身”,您可以从本文中学习许多处理它的方法。 同样,无论何时在测试中使用“随机”,都应定义一个种子值,这样您的“伪随机”结果是可预测的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM