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