-7

Am writing a java program that raises different numbers to powers. Between Math.pow (8,4) and 8*8*8*8, which one takes shorter time to be processed?

Aroniez
  • 99
  • 2
  • 11

4 Answers4

0

Efficiency of Power function is greater than loop.You can check time taken for each functionility in following manner:-

    double i=10;
    java.util.Date dt=new java.util.Date();
    double z=(long) Math.pow (8,i);
    java.util.Date dt1=new java.util.Date();
    System.out.println("Using Power formula:"+(dt1.getTime()-dt.getTime()));
    double t=1;
    for(double k=1;k<=i;k++){
        t*=8;
    }
    java.util.Date dt2=new java.util.Date();
    System.out.println("Using loop :"+(dt2.getTime()-dt1.getTime()));
Nidhish Krishnan
  • 20,593
  • 6
  • 63
  • 76
  • You can't measure such a fast operation with Date... See also http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java – assylias May 12 '14 at 07:20
0

For simple operations like 8^4, a manual multiplication will be faster. A micro benchmark using jmh shows (nanoseconds/op):

Benchmark                 Mode Thr    Cnt  Sec         Mean   Mean error    Units
c.a.p.SO23595573.mult     avgt   1      3    2        3.074        0.022  nsec/op
c.a.p.SO23595573.pow      avgt   1      3    2       68.696        0.186  nsec/op

The code:

private int x = 8;
private int y = 4;

@GenerateMicroBenchmark
public double mult() {
    double result = x;
    for (int i = 0; i < y - 1; i++) {
        result *= x;
    }
    return result;
}

@GenerateMicroBenchmark
public double pow() {
    return Math.pow(x, y);
}
assylias
  • 321,522
  • 82
  • 660
  • 783
-1

Both the functions will be calculated in compile-time and would have the same efficiency.

Dmitry Ginzburg
  • 7,391
  • 2
  • 37
  • 48
-1

Check this small code

long pr=1;
long st=System.currentTimeMillis();
for(int i=0;i<200_00_00_000;i++)
   pr=pr*8;
long en=System.currentTimeMillis();
System.out.println("Executiom time  : "+(en-st));

It'll give you execution time for this code.
Do the same for Math.pow(8,200_00_00_000) and find the difference yourself.

P.S : Math.pow() executes faster.

Nidhish Krishnan
  • 20,593
  • 6
  • 63
  • 76
amanraj
  • 47
  • 1
  • 6
  • -1 Your measurement is flawed (no warmup, you don't use the result of the operation etc.). see also http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java – assylias May 12 '14 at 07:20