score:80
You can compare times using System.nanoTime()
. It will return the time in nanoseconds.
Returns the current value of the most precise available system timer, in nanoseconds.
You could use it like this:
long startTime = System.nanoTime();
// code
long endTime = System.nanoTime();
System.out.println("Took "+(endTime - startTime) + " ns");
Usefull links:
score:0
This is a typical usecase for aspects, for example using Spring AOP:
@Aspect
public class TimerAspect {
private static final Logger LOG = Logger.getLogger(TimerAspect.class);
@Around("com.xyz.myapp.MyClass.myMethod()")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
long startTime = System.nanoTime();
Object retVal = pjp.proceed();
long endTime = System.nanoTime();
LOG.info(String.format("Call to %s.%s with args %s took %s ns", pjp.getTarget(), pjp.getSignature(), Arrays.toString(pjp.getArgs()), endTime - startTime));
return retVal;
}
}
And in your application context:
<aop:aspectj-autoproxy/>
<bean id="myAspect" class="org.xyz.TimerAspect"/>
score:1
If you just want to know how long does your program run use System.currentTimeMillis() in the beginning and end of your program.
score:1
I like using the Apache Commons StopWatch class when I have the library available.
import org.apache.commons.lang3.time.StopWatch;
// ...
StopWatch stopWatch = new StopWatch();
String message = "Task : %s (%s) seconds";
// ...
stopWatch.split();
System.out.println(String.format(message, "10", stopWatch.toSplitString()));
// ...
stopWatch.split();
System.out.println(String.format(message, "20", stopWatch.toSplitString()));
stopWatch.stop();
score:2
You can use 2 APIs provided by System
class
- System.currentTimeMillis() If code takes time in Millisecond range
- System.nanoTime() If code takes time in Nanosecond range
Sample Code
public class TestTimeTaken {
public static void main(String args[]) throws InterruptedException{
long startTimeNanoSecond = System.nanoTime();
long startTimeMilliSecond = System.currentTimeMillis();
//code
Thread.sleep(1000);
//code
long endTimeNanoSecond = System.nanoTime();
long endTimeMilliSecond = System.currentTimeMillis();
System.out.println("Time Taken in "+(endTimeNanoSecond - startTimeNanoSecond) + " ns");
System.out.println("Time Taken in "+(endTimeMilliSecond - startTimeMilliSecond) + " ms");
}
}
score:3
If you have Spring as a dependency of your project (or don't mind adding it), you can use StopWatch
. As the name suggests, once initialized it will count the time until you stop it. You can then check the time taken for a task. Multiple StopWatches can be used simultaneously to multiple tasks keeping the code clean.
Besides keeping your code clean, StopWatches help with formatting the time and other utility methods.
public void myMethod(){
StopWatch stopWatch = new StopWatch();
stopWatch.start("Task1");
// ...
// Do my thing
// ...
stopWatch.stop();
System.out.println("Task executed in " + stopWatch.getTotalTimeSeconds() + "s");
}
score:15
There is no built-in way to see for how long your program has been running. However, you could at the start of the program just store the current time, so that sometime later you can see how much time has elapsed.
public class MyProgram {
private static long startTime = System.currentTimeMillis();
public static void main(String[] args) {
// Do stuff...
// At the end
long endTime = System.currentTimeMillis();
System.out.println("It took " + (endTime - startTime) + " milliseconds");
}
}
Source: stackoverflow.com
Related Query
- How to find time taken to run a Java program?
- Every time I wish to run a java program, java applet pops. How to get the new program be executed and displayed in eclipse?
- How to Run a Simple Java Program in Eclipse?
- How to run a java program using eclim?
- how to run a .jar 1.7 program with an older version java 1.6?
- How do I create a java servlet program and run it using XAMPP Tomcat?
- how to run java program outside eclipse on a server that doesn't have eclipse
- How do i run a Java program from the command line using an Eclipse launch file?
- In Eclipse, how to run a java program as if it's the second argument in the command prompt while running another program as the first argument?
- How can I configure eclipse to run my java program with extra arguments?
- Trying to run a java program in console will give a could not find or load main class error
- how to run embedded pig program using java in eclipse?
- How to run a java program using apache ant and eclipse in windows 64 bit OS?
- How to delete specific file every time the Eclipse Java project is run inside IDE?
- How to run a java program upon compilation of class
- How to run a java applet and swing program in eclipse luna
- How to find execution time of a program in Eclipse?
- How to run a modified java program in eclipse?
- How to run several .txt input files as a test for Java program with output files
- How to find class of interface at run time in Eclipse?
- How can we redirect a Java program console output to multiple files?
- How can I compile a Java program in Eclipse without running it?
- How to simultaneously run all JUnit tests for a Eclipse Java project without Maven?
- How to run Eclipse with different Java version?
- eclipse: how to debug a Java program as a .jar file?
- How to know the command line used by Eclipse to run the java program?
- How to run single Java file from a project in Eclipse?
- How to Debug JUnit tests similar to a regular Java program within Eclipse
- How to run Java Card Connected Edition Web samples on Eclipse?
- Error: Cannot run program "jar": CreateProcess error=2, The system cannot find the file specified
More Query from same tag
- Add library to eclipse
- Adding Eclipse to Gnome Do
- how to refactor/rename macros in Eclipse C++
- Android studio debug-specific AndroidManifest.xml for ACCESS_MOCK_LOCATIONS
- Is there a way to have the package explorer show assemblies that have TODOs in eclipse?
- Customize eclipse-generated code
- How to use robot framework with python in eclipse and How to run the Robot framework tests in eclipse using python interpreters?
- Exclude packages from Eclipse's organize imports
- UnsatisfiedLinkError (cannot find dependent libraries)
- lot of errors during first project in android eclipse
- JSF 2.0 EL tags don't render in browser
- JSP form validation for numbers, dates and values
- Log4j2 not working when OSGI is started from console (Works in Eclipse)
- javacv sample program not running in eclipse?
- Checking/Storing inputs from EditTexts(Android/Java)
- Visual Studio - Automatically refresh class view when changing class
- How to stop Eclipse from indenting extra spaces in this specific scenario?
- eclipse : Missing artifact org.apache.hbase:hbase:jar:1.1.3
- How to import javax.jnlp.*?
- org.eclipse.jetty.server.ssl.SslSelectChannelConnector Missing in new Eclipse Jetty Jars
- Create Maven Project with Nexus Repository OSS 3 [offline]
- Failed to execute goal org.apache.rat:apache-rat-plugin:0.8:check (default) on project giraph-gora: Too many unapproved licenses: 56
- Using a third party lib in an annotation processor with eclipse
- Android test project cannot find app classes
- Save Resource Dialog in Eclipse pops up while editing a java file.
- GWT/Maven Project - Maven dependency order wrong
- How to add a WebContent folder to a Eclipse project
- Eclipse helios issue
- Starting Up Tomcat Server w/ Spring in org.springframework.web.context.ContextLoaderListener
- How to stop project that is already running