Java/Timing: Difference between revisions
From charlesreid1
No edit summary |
|||
| Line 16: | Line 16: | ||
==Timing Snippets of Code== | ==Timing Snippets of Code== | ||
Can make a Stopwatch class that does the following: | |||
* Constructor creates a new "start" variable - the stopwatch class measures time starting at its own creation | |||
* Can call elapsed() method to get elapsed seconds | |||
<pre> | |||
public class Stopwatch { | |||
public Stopwatch() { | |||
this.start = System.currentTimeMillis(); | |||
} | |||
public double elapsed() { | |||
this.end = System.currentTimeMillis(); | |||
return (end-start)/1000.0; | |||
} | |||
} | |||
</pre> | |||
Revision as of 18:13, 31 May 2017
If you want an extremely detailed picture of how much time you're spending in the various parts of your code, you can use a profiler: see Java/Profiling
Basic Timing in Java: Builtin Methods
If you just want to see how much time a piece of code takes to execute, you can use Java's built in time functionality:
long start = System.nanoTime();
doStuff();
long end = System.nanoTime();
long duration = end - start;
System.out.printf("Elapsed time: %03f s\n", duration/1E9);
Timing Snippets of Code
Can make a Stopwatch class that does the following:
- Constructor creates a new "start" variable - the stopwatch class measures time starting at its own creation
- Can call elapsed() method to get elapsed seconds
public class Stopwatch {
public Stopwatch() {
this.start = System.currentTimeMillis();
}
public double elapsed() {
this.end = System.currentTimeMillis();
return (end-start)/1000.0;
}
}