如何计算Java程序执行速度的时间

如何计算Java程序执行速度的时间,java,Java,如何计算java程序的执行时间?我不确定我应该用什么课来做这个 我在寻找类似的东西: // Some timer starts here for (int i = 0; i < length; i++) { // Do something } // End timer here System.out.println("Total execution time: " + totalExecutionTime); //一些计时器从这里开始 for(int i=0;i

如何计算java程序的执行时间?我不确定我应该用什么课来做这个

我在寻找类似的东西:

// Some timer starts here
for (int i = 0; i < length; i++) {
  // Do something
}
// End timer here

System.out.println("Total execution time: " + totalExecutionTime);
//一些计时器从这里开始
for(int i=0;i
您可以利用。在执行前和执行后获取它,然后进行计算。在
系统#currentTimeMillis()
上面,它是首选的,因为它具有更好的精度。根据所使用的硬件和平台的不同,您可能会获得不正确的运行时间间隔。在Windows上使用Core2Duo时,大约0到15毫秒之间实际上无法计算任何内容


更高级的工具是。

您可以获得当前系统时间,以毫秒为单位:

final long startTime = System.currentTimeMillis();
然后你做你要做的:

for (int i = 0; i < length; i++) {
  // Do something
}
final long startTime=System.currentTimeMillis();
for(int i=0;i
看一看。

在循环的顶部使用long
startTime=System.currentTimeMillis()
作为开始时间

put
long-endTime=System.currentTimeMillis()在循环结束之外。您必须减去这些值才能以毫秒为单位获得运行时


如果您希望时间以纳秒为单位,请查看
System.nanoTime()

请注意,在多核CPU上无法可靠地使用
System#nanoTime()
来记录经过的时间时间存在一些问题。。。每个内核都有自己的TSC():此计数器用于获取nano时间(实际上是自CPU启动以来的滴答数)

因此,除非操作系统执行一些TSC时间扭曲以保持内核同步,否则如果在读取初始时间时在一个内核上调度线程,然后切换到另一个内核,则相对时间可能会偶尔出现前后跳跃

我不久前在AMD/Solaris上观察到了这一点,两个时间点之间的运行时间有时会以负值或意外的大正数返回。有一个Solaris内核补丁和BIOS设置需要强制AMD PowerNow!这似乎解决了问题

此外,在VirtualBox环境中使用java
System#nanoTime()
时,还有一个迄今尚未修复的bug;由于
java.util.concurrency
包依赖nano-time,这给我们带来了各种奇怪的间歇性线程问题

另见:

对于简单的东西,System.currentTimeMillis()可以工作

实际上,IDE的设置非常常见,因此在输入“t0”时,它会生成以下行:

final long t0 = System.currentTimeMillis()
但对于更复杂的事情,您可能希望使用统计时间度量,如这里(向下滚动一点,查看表示的时间度量,包括标准偏差等):


您也可以尝试Perf4J。这是一种很好的方法来完成您想要的任务,并有助于在设定的时间跨度内汇总性能统计数据,如平均值、最小值、最大值、标准偏差和每秒事务数。摘自:

StopWatch StopWatch=new LoggingStopWatch();
试一试{
//正在计时的代码块-这只是一个虚拟示例
长睡眠时间=(长)(Math.random()*1000L);
睡眠(睡眠时间);
如果(睡眠时间>500L){
抛出新异常(“抛出异常”);
}
秒表停止(“代码块2.成功”,“睡眠时间<500毫秒”);
}捕获(例外e){
秒表停止(“代码块2.故障”,“异常为:+e”);
}
输出:

INFO: start[1230493236109] time[447] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493236719] time[567] tag[codeBlock2.failure] message[Exception was: java.lang.Exception: Throwing exception]
INFO: start[1230493237286] time[986] tag[codeBlock2.failure] message[Exception was: java.lang.Exception: Throwing exception]
INFO: start[1230493238273] time[194] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493238467] time[463] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493238930] time[310] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493239241] time[610] tag[codeBlock2.failure] message[Exception was: java.lang.Exception: Throwing exception]
INFO: start[1230493239852] time[84] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493239937] time[30] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493239968] time[852] tag[codeBlock2.failure] message[Exception was: java.lang.Exception: Throwing exception]
INFO:start[1230493236109]time[447]tag[codeBlock2.success]message[睡眠时间<500毫秒]
信息:开始[1230493236719]时间[567]标记[codeBlock2.failure]消息[异常为:java.lang.Exception:引发异常]
信息:开始[1230493237286]时间[986]标记[codeBlock2.failure]消息[异常为:java.lang.Exception:引发异常]
信息:开始[1230493238273]时间[194]标记[codeBlock2.success]消息[睡眠时间<500毫秒]
信息:开始[1230493238467]时间[463]标记[codeBlock2.success]消息[睡眠时间<500毫秒]
信息:开始[1230493238930]时间[310]标记[codeBlock2.success]消息[睡眠时间<500毫秒]
信息:开始[1230493239241]时间[610]标记[codeBlock2.failure]消息[Exception was:java.lang.Exception:引发异常]
信息:开始[1230493239852]时间[84]标记[codeBlock2.success]消息[睡眠时间<500毫秒]
信息:开始[1230493239937]时间[30]标记[codeBlock2.success]消息[睡眠时间<500毫秒]
信息:开始[1230493239968]时间[852]标记[codeBlock2.failure]消息[异常为:java.lang.Exception:引发异常]

使用System.currentTimeMillis()是正确的方法。但是,如果您使用命令行,并且希望大致快速地对整个程序计时,请考虑:

time java App
它允许您不修改应用程序的代码和时间。

使用AOP/AspectJ和来自的注释,您可以轻松、紧凑地完成:

@Loggable(Loggable.DEBUG)
public String getSomeResult() {
  // return some value
}

对该方法的每次调用都将以
DEBUG
日志级别发送到SLF4J日志记录设施。每个日志消息都将包含执行时间。

以下是一些在Java中查找执行时间的方法:

1)System.nanoTime()

2)System.currentTimeMillis()

3)即时。立即()

4)Date.getTime()


我创建了一个更高阶的函数,它将要在/中测量的代码作为lambda:

class Utils {

    public static <T> T timeIt(String msg, Supplier<T> s) {
        long startTime = System.nanoTime();
        T t = s.get();
        long endTime = System.nanoTime();
        System.out.println(msg + ": " + (endTime - startTime) + " ns");
        return t;
    }

    public static void timeIt(String msg, Runnable r) {
       timeIt(msg, () -> {r.run(); return null; });
    }
}
输出:

INFO: start[1230493236109] time[447] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493236719] time[567] tag[codeBlock2.failure] message[Exception was: java.lang.Exception: Throwing exception]
INFO: start[1230493237286] time[986] tag[codeBlock2.failure] message[Exception was: java.lang.Exception: Throwing exception]
INFO: start[1230493238273] time[194] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493238467] time[463] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493238930] time[310] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493239241] time[610] tag[codeBlock2.failure] message[Exception was: java.lang.Exception: Throwing exception]
INFO: start[1230493239852] time[84] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493239937] time[30] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493239968] time[852] tag[codeBlock2.failure] message[Exception was: java.lang.Exception: Throwing exception]
代码0:180528 ns
代码1:12003 ns

特别感谢帮助我减少裁员的人。请参阅。

您可以使用秒表

import com.google.common.base.Stopwatch;

Stopwatch timer = Stopwatch.createStarted();
//lines to be executed
System.out.println("Execution time= " + timer.stop());

巴卢斯克的回答也是正确的;这取决于所需的计时器分辨率,以及为什么需要计时。计时器在窗口上
@Loggable(Loggable.DEBUG)
public String getSomeResult() {
  // return some value
}
long startTime = System.nanoTime();
.....your code....
long endTime   = System.nanoTime();
long totalTime = endTime - startTime;
System.out.println("Execution time in nanoseconds  : " + totalTime);
System.out.println("Execution time in milliseconds : " + totalTime / 1000000);
long startTime = System.currentTimeMillis();
.....your code....
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println("Execution time in milliseconds  : " + totalTime);
long startTime = Instant.now().toEpochMilli();
.....your code....
long endTime = Instant.now().toEpochMilli();
long totalTime = endTime - startTime;
System.out.println("Execution time in milliseconds: " + totalTime);
Instant start = Instant.now();
.....your code....
Instant end = Instant.now();
Duration interval = Duration.between(start, end);
System.out.println("Execution time in seconds: " +interval.getSeconds());
long startTime = new Date().getTime();
.....your code....
long endTime = new Date().getTime();
long totalTime = endTime - startTime;
System.out.println("Execution time in milliseconds: " + totalTime);
class Utils {

    public static <T> T timeIt(String msg, Supplier<T> s) {
        long startTime = System.nanoTime();
        T t = s.get();
        long endTime = System.nanoTime();
        System.out.println(msg + ": " + (endTime - startTime) + " ns");
        return t;
    }

    public static void timeIt(String msg, Runnable r) {
       timeIt(msg, () -> {r.run(); return null; });
    }
}
Utils.timeIt("code 0", () ->
        System.out.println("Hallo")
);

// in case you need the result of the lambda
int i = Utils.timeIt("code 1", () ->
        5 * 5
);
import com.google.common.base.Stopwatch;

Stopwatch timer = Stopwatch.createStarted();
//lines to be executed
System.out.println("Execution time= " + timer.stop());