0

I am working in a Java project and we are not using any profiling tool.

Is there a way to find out the time a method takes for execution without using any profiling tool?

Javier
  • 678
  • 5
  • 17
Anand
  • 20,708
  • 48
  • 131
  • 198

3 Answers3

1

Why dont you use something like:

int startTime = System.currentTimeMillis();
methodCall();
int endTime = System.currentTimeMillis();
int totalTime = endTime - startTime;
System.out.println("Time to complete: " + totalTime);

Then you could add the /1000 or whatever to format the time as you desire.

thatidiotguy
  • 8,701
  • 13
  • 60
  • 105
  • 1
    `System.nanoTime()` is usually recommended over `System.currentTimeMillis()` for benchmarking stuff – matt b Sep 21 '12 at 20:51
  • 1
    You've entered the world of quantum physics, just be observing the state, you have/can change it. While probably miniscule to the point of being irrelevant, any additional calls you add to your method (that isn't related to it's operation) "could" potential taint the results. At best you should consider the results as an average. Also, System.out is notoriously slow. If the overall speed of the chain of methods is important, I'd probably use some kind logger (such as log4j) or make my own that allowed me to supply the method and timing information (which could be accumulated and averaged) – MadProgrammer Sep 21 '12 at 21:35
0

Catch System.currentTimeMillis() before start and at the end minus with System.currentTimeMillis(). You will be able to know how much time your method takes to execute.

void fun(){
  long sTime=System.currentTimeMillis();
  ...
  System.out.println("Time Taken to execute-"+System.currentTimeMillis()-sTime+" milis");
}
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
0

Here is a sample program to capture timings:

package com.quicklyjava;

public class Main {

/**
 * @param args
 * @throws InterruptedException
 */
public static void main(String[] args) throws InterruptedException {
    // start time
    long time = System.nanoTime();
    for (int i = 0; i < 5; i++) {
        System.out.println("Sleeping Zzzz... " + i);
        Thread.sleep(1000);
    }

    long difference = System.nanoTime() - time;
    System.out.println("It took " + difference + " nano seconds to finish");

 }

}

And here is the output:

Sleeping Zzzz... 0
Sleeping Zzzz... 1
Sleeping Zzzz... 2
Sleeping Zzzz... 3
Sleeping Zzzz... 4
It took 5007507169 nano seconds to finish
Vineet Rao
  • 56
  • 2