Java Performance Math.tanh ()

I have a Java program that makes many calls to the Math.tanh () function. Out of curiosity, I wanted to make a comparison with C ++. So I wrote two small programs, one in Java and one in C ++, to check.

Java Code:

public class TestTanh { 

    public static void main(String[] args) {

        double t1 = -1.0;
        double t2 = 1.0;
        double step = 1e-8;

        double z = 0.0;
        for(double t=t1; t<=t2; t += step) {
            double y = Math.tanh(t);
            z += y;
        }
        System.out.println("Sum = " + z);
    }
}

and C ++ code:

#include <iostream>
#include <cmath>

using namespace std;

int main() {

    double t1 = -1.0;
    double t2 = 1.0;
    double step = 1e-8;

    double z = 0.0;
    for(double t=t1; t<=t2; t += step) {
        double y = tanh(t);
        z += y;
    }
    cout << "Sum = " << z << "\n";
}

Having compiled and running the programs, I got the following:

$ time java TestTanh
Sum = -0.41281032759865655

real    0m18.372s
user    0m17.961s
sys     0m0.109s

and

$ time ./test_tanh
Sum = -0.41281

real    0m4.022s
user    0m3.641s
sys     0m0.004s

Why does a Java program take about 5 times as long to execute? Could this be due to JIT compiling first? Or is the tanh implementation in Java slower than C ++?

This is a simple test that may have a trivial explanation, but I searched the Internet and could not find the answer. My version of Java

$ java -version
java version "1.6.0_22"
Java(TM) SE Runtime Environment (build 1.6.0_22-b04-307-10M3261)
Java HotSpot(TM) 64-Bit Server VM (build 17.1-b03-307, mixed mode)

tanh , , Java ++ ( 2,3). - tanh , . FastMath Apache Commons, ( - ?). :

C++

real    0m18.031s
user    0m18.007s
sys     0m0.007s

Java lang.Math

real    0m40.739s
user    0m40.032s
sys     0m0.088s

Java org.apache.commons.math.util.FastMath

real    0m46.717s
user    0m46.583s
sys     0m0.372s

, - , , .

+5
5

this, OpenJDK 6 (, , Sun JDK 6) , . . , JVM 18 . JVM.

+3

, Java . , :

  • , , .
  • , +1.0.
  • 2.5 ulps .

C , - tanh(x). , , ?

, , . Java caliper .

+2

" ". , . , Java Hotspot , , , .

, 100% JVM. Java .

, , " ".

+1

++ tanh (a ), , , .

Java , String.length() Sun JVM. Java , hotspot ( ). C ++, ( ).

, Java, Math.tanh . .

+1

, JVM . - Java?

If there is still a big difference after the micro-test is well written, then the possible reason is JNI . The method Math.tanh()and others were implemented in the JVM as native code. The documentation for java.lang.StrictMath says they use the fdlibm library, which is written in C, so it may be useful for you to use this in your tests so that you don't compare two different C libraries.

0
source

All Articles