捕获两条语句之间的执行时间 Java?
我想捕获 Java 类中从语句 A 到语句 B 所需的时间。在这些语句之间进行了许多 Web 服务调用。我想知道java中是否有一些类似秒表的功能可以用来捕获准确的时间?
卡迪
I want to capture the time take to go from statement A to Statement B in a Java class. In between these statements there are many web service calls made. I wanted to know if there is some stop watch like functionality in java that i could use to capture the exact time?
Kaddy
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这将为您提供两次
nanoTime()
调用之间的纳秒数。对于更复杂的方法,有几个解决 Stopwatch 类的重复问题:
This will give you the number of nanoseconds between the two
nanoTime()
calls.For more sophisticated approaches there are several duplicate questions that address Stopwatch classes:
@Ben S 的回答很正确。
但是,应该注意的是,将时间测量语句插入到代码中的方法无法扩展:
System.nanoTime()
的调用并不是免费的!如果您的真正目标是尝试找出应用程序运行缓慢的原因,以便您决定优化哪些内容,那么更好的解决方案是使用 Java 分析器。这样做的优点是您不需要对源代码进行零更改。 (当然,分析并不能为您提供在特定部分花费的确切时间。相反,它为您提供时间比例……这对于决定优化何处更有用。)
@Ben S's answer is spot on.
However, it should be noted that the approach of inserting time measurement statements into your code does not scale:
System.nanoTime()
don't come for free!If your real aim is to try and work out why your application is running slowly so that you decide what what to optimize, then a better solution is to use a Java profiler. This has the advantage that you need to make ZERO changes to your source code. (Of course, profiling doesn't give you the exact times spent in particular sections. Rather, it gives you time proportions ... which is far more useful for deciding where to optimize.)
System.currentTimeMillis 将以毫秒为单位获取它,而 nanoTime 以纳秒为单位获取它。
如果您尝试比较不同技术的性能,请注意 JVM 环境很复杂,因此简单地花费一次是没有意义的。我总是编写一个循环,执行方法 1 几千次,然后执行 System.gc,然后执行方法 2 几千次,然后执行另一个 System.gc,然后循环回来并再次执行整个过程至少五次或六次。这有助于平均垃圾收集、即时编译以及 JVM 中发生的其他神奇事情的时间。
System.currentTimeMillis will get it in milliseconds and nanoTime in nanosceconds.
If you're trying to compare the performance of different techniques, note that the JVM environment is complex so simply taking one time is not meaningful. I always write a loop where I execute method 1 a few thousand times, then do a System.gc, then execute method 2 a few thousands times, then do another System.gc, then loop back and do the whole thing again at least five or six times. This helps to average out time for garbage collection, just-in-time compiles, and other magic things happening in the JVM.