summaryrefslogtreecommitdiff
path: root/src/main/java/org/linaro/benchmarks/math/MathPartialSums.java
blob: 0d7919a0beb717175a24f7678cd309db1098eafa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
 * Copyright (C) 2015 Linaro Limited. Ported to Java from:
 *  https://github.com/WebKit/webkit/blob/master/PerformanceTests/SunSpider/tests/sunspider-1.0.2/math-partial-sums.js
 *
 * Description:     Partial sum calculation of a series using Math().pow(),
 *                  Math.sin() and Math.cos().
 * Main Focus:      Floating-Point operations, Math.[pow(), sin(), cos()].
 *
 */

// The Computer Language Shootout
// http://shootout.alioth.debian.org/
// contributed by Isaac Gouy

// http://benchmarksgame.alioth.debian.org/license.html  (BSD 3-clause license)
// See NOTICE file for license.

package org.linaro.benchmarks.math;

import java.lang.Exception;
import java.lang.Math;
import java.lang.System;
import org.openjdk.jmh.annotations.*;
import java.util.concurrent.TimeUnit;

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Benchmark)

public class MathPartialSums {
  private static final double PARTIAL_SUMS_EXPECTED = 33.97380678948515;

  private static double partialSums(int n) {
    double a1;
    double a2;
    double a3;
    double a4;
    double a5;
    double a6;
    double a7;
    double a8;
    double a9;
    double k2;
    double k3;
    double sk;
    double ck;
    double twothirds = 2.0 / 3.0;
    double alt = -1.0;

    a1 = a2 = a3 = a4 = a5 = a6 = a7 = a8 = a9 = 0.0;
    for (int k = 1; k <= n; k++) {
      k2 = k * k;
      k3 = k2 * k;
      sk = Math.sin(k);
      ck = Math.cos(k);
      alt = -alt;

      a1 += Math.pow(twothirds, k - 1);
      a2 += Math.pow(k, -0.5);
      a3 += 1.0 / (k * (k + 1.0));
      a4 += 1.0 / (k3 * sk * sk);
      a5 += 1.0 / (k3 * ck * ck);
      a6 += 1.0 / k;
      a7 += 1.0 / k2;
      a8 += alt / k;
      a9 += alt / (2 * k - 1);
    }
    return a6 + a7 + a8 + a9;
  }
  @Benchmark
  public void jmhTimeMathPartialSums() {
    for (int j = 1024; j <= 5000; j *= 2) {
      partialSums(j);
    }
  }
}