From Walloping Frog, 7 Months ago, written in Java.
Embed
  1. import org.openjdk.jmh.annotations.Benchmark;
  2. import org.openjdk.jmh.annotations.Fork;
  3. import org.openjdk.jmh.annotations.Measurement;
  4. import org.openjdk.jmh.annotations.Warmup;
  5. import org.openjdk.jmh.infra.Blackhole;
  6.  
  7. @Warmup(iterations = 10)
  8. @Measurement(iterations = 5)
  9. @Fork(value = 1)
  10. public class ComparsionBenchmark {
  11.  
  12.     private static final byte[] hash1 = new byte[] { -49, -73, 127, -112, -128, -10, -43, -34, -29, -18, -58, -69, -44,
  13.             -64, -47, -18, -37, -48, -87, -67, -59, -46, -31, -60, -44, -56, -68, -60, -46, -40, -44, -45, -54, -41, -46, -43, -52, -46, -47, -43 };
  14.     private static final byte[] hash2 = new byte[] { 23, -73, -74, 126, -128, 41, 36, -7, 81, 22, -58, 57, 31, -8, 25,
  15.             34, 13, 10, 24, 42, 22, 5, 36, 18, 28, 32, 4, 34, 22, 6, 37, 9, 37, 10, 23, 28, 11, 38, 10, 22 };
  16.  
  17.     public static double getSimilarity(byte[] x_coeffs, byte[] y_coeffs) {
  18.         int N = x_coeffs.length;
  19.         double[] r = new double[N];
  20.         double sumx = 0.0D;
  21.         double sumy = 0.0D;
  22.  
  23.         for(int i = 0; i < N; ++i) {
  24.             sumx += (double)(x_coeffs[i] & 255);
  25.             sumy += (double)(y_coeffs[i] & 255);
  26.         }
  27.  
  28.         double meanx = sumx / (double)N;
  29.         double meany = sumy / (double)N;
  30.         double max = 0.0D;
  31.  
  32.         for(int d = 0; d < N; ++d) {
  33.             double num = 0.0D;
  34.             double denx = 0.0D;
  35.             double deny = 0.0D;
  36.  
  37.             for(int i = 0; i < N; ++i) {
  38.                 num += ((double)x_coeffs[i] - meanx) * ((double)y_coeffs[(N + i - d) % N] - meany);
  39.                 denx += Math.pow((double)x_coeffs[i] - meanx, 2.0D);
  40.                 deny += Math.pow((double)y_coeffs[(N + i - d) % N] - meany, 2.0D);
  41.             }
  42.  
  43.             r[d] = num / Math.sqrt(denx * deny);
  44.             if (r[d] > max) {
  45.                 max = r[d];
  46.             }
  47.         }
  48.  
  49.         return max;
  50.     }
  51.  
  52.     @Benchmark
  53.     public void original(Blackhole sink) {
  54.         sink.consume(getSimilarity(hash1, hash2) >= 1.0);
  55.     }
  56.  
  57. }