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
, - , , .