Timing an action
I'm parsing a file with a few actions, and I want to measure the time that it ta开发者_开发问答kes to perform those actions.
What is the best way to do this and print the time?
Update: If you're not opposed to using external libraries and you're on JDK 5+, Google Guava has a Stopwatch that uses System.nanoTime()
. It is not associated with absolute system or wall clock time but instead is useful only when calculating elapsed time, but this is exactly what you want.
Otherwise, you can use System.currentTimeMillis()
which returns the current system time in milliseconds as a long integer.
long start = System.currentTimeMillis();
// ... perform operations ...
long time = System.currentTimeMillis() - start;
System.out.println("Operation took " + time + "ms");
Timing short-run operations can be very tricky, especially when you run them in a loop to amortize it across multiple runs. You're at the whims of the task scheduler of the operating system and Java's internal thread scheduler.
To mitigate these issues, average the time across multiple runs and move console output operations out of the timing if possible. Just keep in mind that you're not going to get exact numbers.
This is how you usually measure execution time:
long start = System.currentTimeMillis();
//perform action
System.out.println("It took " + (System.currentTimeMillis() - start) + "ms");
Not sure what you mean by actions, but if you want to see how long a piece of code takes:
long start = System.nanoTime();
//Your code here
long timeElapsed = System.nanoTime() - start;
System.out.println(timeElapsed);
That will print the number of nanoseconds taken
I'd use my IDE's profiler or jvisualvm
.
long start=System.currentTimeMillis();
//your action code
long end=System.currentTimeMillis();
int durationInMillis=end-start;
精彩评论