如何找到运行 Java 程序所需的时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6646467/
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 find time taken to run a Java program?
提问by MK1
I have a Java application that I've been working on and I just realized that the program has to return a value in less than a minute, but don't know how to find or display the time taken to run the program. How to find time taken to run a program?
我有一个一直在开发的 Java 应用程序,我刚刚意识到该程序必须在不到一分钟的时间内返回一个值,但不知道如何查找或显示运行该程序所需的时间。如何找到运行程序所需的时间?
采纳答案by Jigar Joshi
You can compare times using System.nanoTime()
. It will return the time in nanoseconds.
您可以使用 比较时间System.nanoTime()
。它将以纳秒为单位返回时间。
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:
有用的链接:
回答by Jesper
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");
}
}
回答by AlexR
If you just want to know how long does your program run use System.currentTimeMillis() in the beginning and end of your program.
如果您只想知道程序运行了多长时间,请在程序的开头和结尾使用 System.currentTimeMillis()。
回答by Adriaan Koster
This is a typical usecase for aspects, for example using Spring AOP:
这是方面的典型用例,例如使用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"/>
回答by Felipe Le?o
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.
如果您将 Spring 作为项目的依赖项(或不介意添加它),则可以使用StopWatch
. 顾名思义,一旦初始化,它就会计算时间,直到你停止它。然后,您可以检查任务所用的时间。多个秒表可以同时用于多个任务,保持代码整洁。
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");
}
回答by Om Sao
You can use 2 APIs provided by System
class
您可以使用System
类提供的 2 个 API
- System.currentTimeMillis()If code takes time in Millisecond range
- System.nanoTime()If code takes time in Nanosecond range
- System.currentTimeMillis()如果代码在毫秒范围内花费时间
- System.nanoTime()如果代码在纳秒范围内花费时间
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");
}
}
回答by Gabriel Gates
I like using the Apache Commons StopWatch class when I have the library available.
当我有可用的库时,我喜欢使用 Apache Commons StopWatch 类。
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();