Yesterday I saw a question why it Math.pow(int,int)works so slowly, but the question was poorly formulated and showed no research efforts, so it quickly closed.
I did a little test on my own and found that the method Math.powreally did run very slowly compared to my own naive implementation (which is not even particularly efficiently implemented) when dealing with whole arguments. Below is the code I checked to verify this:
class PowerTest {
public static double myPow(int base, int exponent) {
if(base == 0) return 0;
if(exponent == 0) return 1;
int absExponent = (exponent < 0)? exponent * -1 : exponent;
double result = base;
for(int i = 1; i < absExponent; i++) {
result *= base;
}
if(exponent < 1) result = 1 / result;
return result;
}
public static void main(String args[]) {
long startTime, endTime;
startTime = System.nanoTime();
for(int i = 0; i < 5000000; i++) {
Math.pow(2,2);
}
endTime = System.nanoTime();
System.out.printf("Math.pow took %d milliseconds.\n", (endTime - startTime) / 1000000);
startTime = System.nanoTime();
for(int i = 0; i < 5000000; i++) {
myPow(2,2);
}
endTime = System.nanoTime();
System.out.printf("myPow took %d milliseconds.\n", (endTime - startTime) / 1000000);
}
}
(Linux Intel x86_64) , Math.pow 10 , myPow 2 . , Math.pow 5x .
, grepcode, Math.pow (double, double) StrictMath.pow, .
, Math pow, , . , , double, , , . , , ( , - JVM, , C ). , , , .
, Math.pow , myPow, ?