如何测量 Java 代码所花费的时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20211648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to measure time taken by Java code?
提问by Mangat Rai Modi
I need to analyze complexity for some algorithms in Java. For that I am planning to give large number of input and measure the time taken by Java implementation. What is the most precise and accurate way to check time between some lines of code? I need precision in milliseconds...
我需要分析 Java 中某些算法的复杂性。为此,我计划提供大量输入并测量 Java 实现所花费的时间。检查某些代码行之间的时间的最精确和准确的方法是什么?我需要以毫秒为单位的精度...
采纳答案by creichen
You can get nanosecond resolution, even, using System.nanoTime()
.
您甚至可以使用System.nanoTime()
.
However, you may want to consider the points in the following:
但是,您可能需要考虑以下几点:
回答by user987339
Use System.nanoTime()
or System.currentTimeMillis()
to get both start and finish time of your code. Be aware that micro-benchmarks measure only basic aspects of JVM performance. Be aware of warm up phase for JVM, after which JITis started.
使用System.nanoTime()
或System.currentTimeMillis()
获取代码的开始和结束时间。请注意,微基准测试仅衡量 JVM 性能的基本方面。请注意 JVM 的预热阶段,之后JIT将启动。
回答by Foolish
long start = System.currentTimeMillis();
// your code
long end = System.currentTimeMillis();
long diff = end-start;
or
或者
long start = System.nanoTime();
// your code
long end = System.nanoTime();
long diff = end-start;
long diffInMillis = diff/1000000;
回答by Little Child
Say you have a particular method that you would like to put under the microscope. You can do that as follows:
假设您有一个特定的方法想要放在显微镜下。你可以这样做:
long time1 = System.nanoTime();
thatMethod();
long time2 = System.nanoTime();
long timeTaken = time2 - time1;
System.out.println("Time taken " + timeTaken + " ns");
Computers are really fast so it may happen that time difference when using getTimeMillis()
maybe zero. Hence, use nanoTime()
计算机真的很快,所以使用getTimeMillis()
零时可能会发生时差。因此,使用nanoTime()
You can also use Caliper
. They have a video to get started. Plus, thoroughly read the answer pointed to by creichen
. It has a lot of great stuff in it.
您也可以使用Caliper
. 他们有一个视频可以开始。另外,请仔细阅读creichen
. 它里面有很多很棒的东西。
回答by Bhupendra
long startTime = System.currentTimeMillis();
//code lines whose time you want to calculate
long endTime = System.currentTimeMillis();
System.out.println("Took "+(endTime - startTime) + " ms");
回答by Hussain Pirosha
Use a library such as Speed4j. This shall not only benchmark the calls but also provide statistics in logs, also you can see them remotely via JMX. It is better of using such a library rather than placing System.current.. calls all over the code.
使用诸如Speed4j 之类的库。这不仅可以对调用进行基准测试,还可以在日志中提供统计信息,您还可以通过 JMX 远程查看它们。最好使用这样的库,而不是在整个代码中放置 System.current.. 调用。