Dia*_*ism 1150
总有一种老式的方式:
long startTime = System.nanoTime();
methodToTime();
long endTime = System.nanoTime();
long duration = (endTime - startTime); //divide by 1000000 to get milliseconds.
Run Code Online (Sandbox Code Playgroud)
MBC*_*ook 185
我选择简单的答案.适合我.
long startTime = System.currentTimeMillis();
doReallyLongThing();
long endTime = System.currentTimeMillis();
System.out.println("That took " + (endTime - startTime) + " milliseconds");
Run Code Online (Sandbox Code Playgroud)
它运作得很好.分辨率显然只有毫秒,你可以用System.nanoTime()做得更好.两者都存在一些限制(操作系统计划切片等),但这很有效.
几次运行的平均值(越多越好),你会得到一个不错的主意.
小智 170
拜托了伙计们!没有人提到Guava的方法(这可以说是很棒):
import com.google.common.base.Stopwatch;
Stopwatch timer = Stopwatch.createStarted();
//method invocation
LOG.info("Method took: " + timer.stop());
Run Code Online (Sandbox Code Playgroud)
好的是,Stopwatch.toString()可以很好地选择测量的时间单位.即如果值很小,它将输出38 ns,如果它很长,它将显示5m 3s
更好的:
Stopwatch timer = Stopwatch.createUnstarted();
for (...) {
timer.start();
methodToTrackTimeFor();
timer.stop();
methodNotToTrackTimeFor();
}
LOG.info("Method took: " + timer);
Run Code Online (Sandbox Code Playgroud)
注意:Google Guava需要Java 1.6+
Suf*_*ori 133
使用Java 8的新API中的Instant和Duration,
Instant start = Instant.now();
Thread.sleep(5000);
Instant end = Instant.now();
System.out.println(Duration.between(start, end));
Run Code Online (Sandbox Code Playgroud)
输出,
PT5S
Run Code Online (Sandbox Code Playgroud)
Jam*_*hek 85
使用分析器(JProfiler,Netbeans Profiler,Visual VM,Eclipse Profiler等).您将获得最准确的结果,并且是最不具侵入性的.它们使用内置的JVM机制进行性能分析,如果需要,还可以为您提供堆栈跟踪,执行路径和更全面的结果等额外信息.
使用完全集成的分析器时,分析方法很简单.右键单击,Profiler - >添加到根方法.然后像运行测试运行或调试器一样运行探查器.
Yas*_*ash 85
将所有可能的方式聚集在一起.
Date startDate = Calendar.getInstance().getTime();
long d_StartTime = new Date().getTime();
Thread.sleep(1000 * 4);
Date endDate = Calendar.getInstance().getTime();
long d_endTime = new Date().getTime();
System.out.format("StartDate : %s, EndDate : %s \n", startDate, endDate);
System.out.format("Milli = %s, ( D_Start : %s, D_End : %s ) \n", (d_endTime - d_StartTime),d_StartTime, d_endTime);
Run Code Online (Sandbox Code Playgroud)
long startTime = System.currentTimeMillis();
Thread.sleep(1000 * 4);
long endTime = System.currentTimeMillis();
long duration = (endTime - startTime);
System.out.format("Milli = %s, ( S_Start : %s, S_End : %s ) \n", duration, startTime, endTime );
System.out.println("Human-Readable format : "+millisToShortDHMS( duration ) );
Run Code Online (Sandbox Code Playgroud)
人类可读格式
public static String millisToShortDHMS(long duration) {
String res = ""; // java.util.concurrent.TimeUnit;
long days = TimeUnit.MILLISECONDS.toDays(duration);
long hours = TimeUnit.MILLISECONDS.toHours(duration) -
TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(duration));
long minutes = TimeUnit.MILLISECONDS.toMinutes(duration) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(duration));
long seconds = TimeUnit.MILLISECONDS.toSeconds(duration) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration));
long millis = TimeUnit.MILLISECONDS.toMillis(duration) -
TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(duration));
if (days == 0) res = String.format("%02d:%02d:%02d.%04d", hours, minutes, seconds, millis);
else res = String.format("%dd %02d:%02d:%02d.%04d", days, hours, minutes, seconds, millis);
return res;
}
Run Code Online (Sandbox Code Playgroud)
番石榴:谷歌 秒表JAR « 秒表的一个目标是测量经过的时间,以纳秒为单位.
com.google.common.base.Stopwatch g_SW = Stopwatch.createUnstarted();
g_SW.start();
Thread.sleep(1000 * 4);
g_SW.stop();
System.out.println("Google StopWatch : "+g_SW);
Run Code Online (Sandbox Code Playgroud)
Apache Commons Lang JAR « StopWatch为时序提供了一个方便的API.
org.apache.commons.lang3.time.StopWatch sw = new StopWatch();
sw.start();
Thread.sleep(1000 * 4);
sw.stop();
System.out.println("Apache StopWatch : "+ millisToShortDHMS(sw.getTime()) );
Run Code Online (Sandbox Code Playgroud)
JODA -TIME
public static void jodaTime() throws InterruptedException, ParseException{
java.text.SimpleDateFormat ms_SDF = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
String start = ms_SDF.format( new Date() ); // java.util.Date
Thread.sleep(10000);
String end = ms_SDF.format( new Date() );
System.out.println("Start:"+start+"\t Stop:"+end);
Date date_1 = ms_SDF.parse(start);
Date date_2 = ms_SDF.parse(end);
Interval interval = new org.joda.time.Interval( date_1.getTime(), date_2.getTime() );
Period period = interval.toPeriod(); //org.joda.time.Period
System.out.format("%dY/%dM/%dD, %02d:%02d:%02d.%04d \n",
period.getYears(), period.getMonths(), period.getDays(),
period.getHours(), period.getMinutes(), period.getSeconds(), period.getMillis());
}
Run Code Online (Sandbox Code Playgroud)
来自Java 8的Java日期时间API « 持续时间对象表示两个Instant对象之间的时间段.
Instant start = java.time.Instant.now();
Thread.sleep(1000);
Instant end = java.time.Instant.now();
Duration between = java.time.Duration.between(start, end);
System.out.println( between ); // PT1.001S
System.out.format("%dD, %02d:%02d:%02d.%04d \n", between.toDays(),
between.toHours(), between.toMinutes(), between.getSeconds(), between.toMillis()); // 0D, 00:00:01.1001
Run Code Online (Sandbox Code Playgroud)
Spring Framework提供了 StopWatch实用程序类来测量Java中的已用时间.
StopWatch sw = new org.springframework.util.StopWatch();
sw.start("Method-1"); // Start a named task
Thread.sleep(500);
sw.stop();
sw.start("Method-2");
Thread.sleep(300);
sw.stop();
sw.start("Method-3");
Thread.sleep(200);
sw.stop();
System.out.println("Total time in milliseconds for all tasks :\n"+sw.getTotalTimeMillis());
System.out.println("Table describing all tasks performed :\n"+sw.prettyPrint());
System.out.format("Time taken by the last task : [%s]:[%d]",
sw.getLastTaskName(),sw.getLastTaskTimeMillis());
System.out.println("\n Array of the data for tasks performed « Task Name: Time Taken");
TaskInfo[] listofTasks = sw.getTaskInfo();
for (TaskInfo task : listofTasks) {
System.out.format("[%s]:[%d]\n",
task.getTaskName(), task.getTimeMillis());
}
Run Code Online (Sandbox Code Playgroud)
输出:
Total time in milliseconds for all tasks :
999
Table describing all tasks performed :
StopWatch '': running time (millis) = 999
-----------------------------------------
ms % Task name
-----------------------------------------
00500 050% Method-1
00299 030% Method-2
00200 020% Method-3
Time taken by the last task : [Method-3]:[200]
Array of the data for tasks performed « Task Name: Time Taken
[Method-1]:[500]
[Method-2]:[299]
[Method-3]:[200]
Run Code Online (Sandbox Code Playgroud)
ska*_*man 38
这可能不是你想要我说的,但这是AOP的一个很好的用法.在你的方法周围打一个代理拦截器,并在那里做时间.
可悲的是,AOP的内容,原因和方式超出了这个答案的范围,但这就是我可能做到的.
编辑:如果您热衷于此,这里有一个指向 Spring AOP 的链接,可以帮助您入门.这是Iive最容易实现的AOP实现.
另外,鉴于其他人的非常简单的建议,我应该补充一点,AOP适用于你不想要时间来侵入代码的东西.但在许多情况下,这种简单易行的方法很好.
Ton*_*CZE 37
System.currentTimeMillis();这不是衡量算法性能的好方法.它衡量用户观看计算机屏幕时的总体时间.它还包括在后台运行在计算机上的所有其他内容所消耗的时间.如果您的工作站上运行了很多程序,这可能会产生巨大的差异.
正确的方法是使用java.lang.management包.
来自http://nadeausoftware.com/articles/2008/03/java_tip_how_get_cpu_and_user_time_benchmarking网站:
getCpuTime() 方法给你的总和:
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
public class CPUUtils {
/** Get CPU time in nanoseconds. */
public static long getCpuTime( ) {
ThreadMXBean bean = ManagementFactory.getThreadMXBean( );
return bean.isCurrentThreadCpuTimeSupported( ) ?
bean.getCurrentThreadCpuTime( ) : 0L;
}
/** Get user time in nanoseconds. */
public static long getUserTime( ) {
ThreadMXBean bean = ManagementFactory.getThreadMXBean( );
return bean.isCurrentThreadCpuTimeSupported( ) ?
bean.getCurrentThreadUserTime( ) : 0L;
}
/** Get system time in nanoseconds. */
public static long getSystemTime( ) {
ThreadMXBean bean = ManagementFactory.getThreadMXBean( );
return bean.isCurrentThreadCpuTimeSupported( ) ?
(bean.getCurrentThreadCpuTime( ) - bean.getCurrentThreadUserTime( )) : 0L;
}
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*fan 26
使用Java 8,您可以使用每种常规方法执行类似的操作:
Object returnValue = TimeIt.printTime(() -> methodeWithReturnValue());
//do stuff with your returnValue
Run Code Online (Sandbox Code Playgroud)
与TimeIt像:
public class TimeIt {
public static <T> T printTime(Callable<T> task) {
T call = null;
try {
long startTime = System.currentTimeMillis();
call = task.call();
System.out.print((System.currentTimeMillis() - startTime) / 1000d + "s");
} catch (Exception e) {
//...
}
return call;
}
}
Run Code Online (Sandbox Code Playgroud)
使用这种方法,您可以在代码中的任何位置轻松进行时间测量而不会破坏它.在这个简单的例子中,我只打印时间.你可以为TimeIt添加一个Switch,例如只在DebugMode中打印时间.
如果你正在使用Function,你可以做这样的事情:
Function<Integer, Integer> yourFunction= (n) -> {
return IntStream.range(0, n).reduce(0, (a, b) -> a + b);
};
Integer returnValue = TimeIt.printTime2(yourFunction).apply(10000);
//do stuff with your returnValue
public static <T, R> Function<T, R> printTime2(Function<T, R> task) {
return (t) -> {
long startTime = System.currentTimeMillis();
R apply = task.apply(t);
System.out.print((System.currentTimeMillis() - startTime) / 1000d
+ "s");
return apply;
};
}
Run Code Online (Sandbox Code Playgroud)
小智 17
我们也可以使用Apache公共的StopWatch类来测量时间.
示例代码
org.apache.commons.lang.time.StopWatch sw = new org.apache.commons.lang.time.StopWatch();
System.out.println("getEventFilterTreeData :: Start Time : " + sw.getTime());
sw.start();
// Method execution code
sw.stop();
System.out.println("getEventFilterTreeData :: End Time : " + sw.getTime());
Run Code Online (Sandbox Code Playgroud)
Han*_*örr 15
如果你不使用工具并且想要以低执行时间计时方法,那么只需要很小的一点:执行它多次,每次执行的次数加倍,直到你达到一秒左右.因此,调用System.nanoTime等的时间,以及System.nanoTime的准确性确实会对结果产生很大影响.
int runs = 0, runsPerRound = 10;
long begin = System.nanoTime(), end;
do {
for (int i=0; i<runsPerRound; ++i) timedMethod();
end = System.nanoTime();
runs += runsPerRound;
runsPerRound *= 2;
} while (runs < Integer.MAX_VALUE / 2 && 1000000000L > end - begin);
System.out.println("Time for timedMethod() is " +
0.000000001 * (end-begin) / runs + " seconds");
Run Code Online (Sandbox Code Playgroud)
当然,关于使用挂钟的注意事项适用:JIT编译的影响,多线程/进程等.因此,您需要首先执行该方法很多次,这样JIT编译器才能完成其工作,然后多次重复此测试并执行最短的执行时间.
小智 13
我们正在使用AspectJ和Java注释来实现此目的.如果我们需要了解方法的执行时间,我们可以简单地注释它.更高级的版本可以使用可在运行时启用和禁用的自己的日志级别.
public @interface Trace {
boolean showParameters();
}
@Aspect
public class TraceAspect {
[...]
@Around("tracePointcut() && @annotation(trace) && !within(TraceAspect)")
public Object traceAdvice ( ProceedingJintPoint jP, Trace trace ) {
Object result;
// initilize timer
try {
result = jp.procced();
} finally {
// calculate execution time
}
return result;
}
[...]
}
Run Code Online (Sandbox Code Playgroud)
ice*_*erg 11
真的很好的代码.
http://www.rgagnon.com/javadetails/java-0585.html
import java.util.concurrent.TimeUnit;
long startTime = System.currentTimeMillis();
........
........
........
long finishTime = System.currentTimeMillis();
String diff = millisToShortDHMS(finishTime - startTime);
/**
* converts time (in milliseconds) to human-readable format
* "<dd:>hh:mm:ss"
*/
public static String millisToShortDHMS(long duration) {
String res = "";
long days = TimeUnit.MILLISECONDS.toDays(duration);
long hours = TimeUnit.MILLISECONDS.toHours(duration)
- TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(duration));
long minutes = TimeUnit.MILLISECONDS.toMinutes(duration)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(duration));
long seconds = TimeUnit.MILLISECONDS.toSeconds(duration)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration));
if (days == 0) {
res = String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
else {
res = String.format("%dd%02d:%02d:%02d", days, hours, minutes, seconds);
}
return res;
}
Run Code Online (Sandbox Code Playgroud)
Bas*_*que 11
仅供参考,JEP 230:Microbenchmark Suite是一项OpenJDK提案,旨在:
在JDK源代码中添加一套基本的微基准测试,使开发人员可以轻松运行现有的微基准测试并创建新的基准测试.
这个提议没有为Java 9做好准备,但可能会在以后添加.
与此同时,您可能需要查看提案所基于的Java Microbenchmark Harness(JMH)项目.
mer*_*hik 10
你可以使用Perf4j.很酷的实用程序.用法很简单
String watchTag = "target.SomeMethod";
StopWatch stopWatch = new LoggingStopWatch(watchTag);
Result result = null; // Result is a type of a return value of a method
try {
result = target.SomeMethod();
stopWatch.stop(watchTag + ".success");
} catch (Exception e) {
stopWatch.stop(watchTag + ".fail", "Exception was " + e);
throw e;
}
Run Code Online (Sandbox Code Playgroud)
更多信息可以在开发人员指南中找到
编辑:项目似乎已经死了
Bha*_*ani 10
在 Spring 框架中,我们有一个名为 StopWatch 的调用(org.springframework.util.StopWatch)
//measuring elapsed time using Spring StopWatch
StopWatch watch = new StopWatch();
watch.start();
for(int i=0; i< 1000; i++){
Object obj = new Object();
}
watch.stop();
System.out.println("Total execution time to create 1000 objects in Java using StopWatch in millis: "
+ watch.getTotalTimeMillis());
Run Code Online (Sandbox Code Playgroud)
new Timer(""){{
// code to time
}}.timeMe();
public class Timer {
private final String timerName;
private long started;
public Timer(String timerName) {
this.timerName = timerName;
this.started = System.currentTimeMillis();
}
public void timeMe() {
System.out.println(
String.format("Execution of '%s' takes %dms.",
timerName,
started-System.currentTimeMillis()));
}
}
Run Code Online (Sandbox Code Playgroud)
我基本上做了这方面的变化,但考虑到热点编译的工作原理,如果你想获得准确的结果,你需要抛出前几个测量并确保你在现实世界中使用该方法(特定于应用程序)应用程序.
如果JIT决定编译它,你的数字会有很大差异.所以请注意
使用@Loggable来自jcabi-aspects的 AOP/AspectJ和注释,您可以轻松简洁地完成:
@Loggable(Loggable.DEBUG)
public String getSomeResult() {
// return some value
}
Run Code Online (Sandbox Code Playgroud)
每次调用此方法都将发送到具有DEBUG日志记录级别的SLF4J日志记录工具.每条日志消息都包含执行时间.
有几种方法可以做到这一点.我通常会回到使用这样的东西:
long start = System.currentTimeMillis();
// ... do something ...
long end = System.currentTimeMillis();
Run Code Online (Sandbox Code Playgroud)
与System.nanoTime()相同的事情;
对于基准测试方面的更多内容,似乎还有这个:http://jetm.void.fm/从未尝试过.
根据JavaDoc,Spring提供了一个实用程序类org.springframework.util.StopWatch:
简单的秒表,允许为多个任务计时,公开总运行时间和每个命名任务的运行时间。
用法:
StopWatch stopWatch = new StopWatch("Performance Test Result");
stopWatch.start("Method 1");
doSomething1();//method to test
stopWatch.stop();
stopWatch.start("Method 2");
doSomething2();//method to test
stopWatch.stop();
System.out.println(stopWatch.prettyPrint());
Run Code Online (Sandbox Code Playgroud)
输出:
StopWatch 'Performance Test Result': running time (millis) = 12829
-----------------------------------------
ms % Task name
-----------------------------------------
11907 036% Method 1
00922 064% Method 2
Run Code Online (Sandbox Code Playgroud)
与方面:
@Around("execution(* my.package..*.*(..))")
public Object logTime(ProceedingJoinPoint joinPoint) throws Throwable {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Object retVal = joinPoint.proceed();
stopWatch.stop();
log.info(" execution time: " + stopWatch.getTotalTimeMillis() + " ms");
return retVal;
}
Run Code Online (Sandbox Code Playgroud)
我已经编写了一种方法,以一种易于阅读的形式打印该方法的执行时间。例如,要计算100万的阶乘,大约需要9分钟。因此执行时间被打印为:
Execution Time: 9 Minutes, 36 Seconds, 237 MicroSeconds, 806193 NanoSeconds
Run Code Online (Sandbox Code Playgroud)
代码在这里:
public class series
{
public static void main(String[] args)
{
long startTime = System.nanoTime();
long n = 10_00_000;
printFactorial(n);
long endTime = System.nanoTime();
printExecutionTime(startTime, endTime);
}
public static void printExecutionTime(long startTime, long endTime)
{
long time_ns = endTime - startTime;
long time_ms = TimeUnit.NANOSECONDS.toMillis(time_ns);
long time_sec = TimeUnit.NANOSECONDS.toSeconds(time_ns);
long time_min = TimeUnit.NANOSECONDS.toMinutes(time_ns);
long time_hour = TimeUnit.NANOSECONDS.toHours(time_ns);
System.out.print("\nExecution Time: ");
if(time_hour > 0)
System.out.print(time_hour + " Hours, ");
if(time_min > 0)
System.out.print(time_min % 60 + " Minutes, ");
if(time_sec > 0)
System.out.print(time_sec % 60 + " Seconds, ");
if(time_ms > 0)
System.out.print(time_ms % 1E+3 + " MicroSeconds, ");
if(time_ns > 0)
System.out.print(time_ns % 1E+6 + " NanoSeconds");
}
}
Run Code Online (Sandbox Code Playgroud)
如果您想要挂钟时间
long start_time = System.currentTimeMillis();
object.method();
long end_time = System.currentTimeMillis();
long execution_time = end_time - start_time;
Run Code Online (Sandbox Code Playgroud)
long startTime = System.currentTimeMillis();
// code goes here
long finishTime = System.currentTimeMillis();
long elapsedTime = finishTime - startTime; // elapsed time in milliseconds
Run Code Online (Sandbox Code Playgroud)
正如“ skaffman”所说,使用AOP OR可以使用运行时字节码编织,就像单元测试方法覆盖工具用来透明地将计时信息添加到调用的方法一样。
您可以查看Emma等开放源代码工具所使用的代码(http://downloads.sourceforge.net/emma/emma-2.0.5312-src.zip?modtime=1118607545&big_mirror=0)。另一个开放源代码覆盖工具是http://prdownloads.sourceforge.net/cobertura/cobertura-1.9-src.zip?download。
如果您最终设法按照自己的意愿去做,请。与您的蚂蚁任务/罐子在这里与社区共享。
您可以使用提供各种测量仪器的Metrics库。添加依赖项:
<dependencies>
<dependency>
<groupId>io.dropwizard.metrics</groupId>
<artifactId>metrics-core</artifactId>
<version>${metrics.version}</version>
</dependency>
</dependencies>
Run Code Online (Sandbox Code Playgroud)
并根据您的环境进行配置。
可以使用@Timed注释方法:
@Timed
public void exampleMethod(){
// some code
}
Run Code Online (Sandbox Code Playgroud)
或用Timer包装的一段代码:
final Timer timer = metricsRegistry.timer("some_name");
final Timer.Context context = timer.time();
// timed code
context.stop();
Run Code Online (Sandbox Code Playgroud)
汇总指标可以导出到控制台,JMX,CSV或其他。
@Timed 指标输出示例:
com.example.ExampleService.exampleMethod
count = 2
mean rate = 3.11 calls/minute
1-minute rate = 0.96 calls/minute
5-minute rate = 0.20 calls/minute
15-minute rate = 0.07 calls/minute
min = 17.01 milliseconds
max = 1006.68 milliseconds
mean = 511.84 milliseconds
stddev = 699.80 milliseconds
median = 511.84 milliseconds
75% <= 1006.68 milliseconds
95% <= 1006.68 milliseconds
98% <= 1006.68 milliseconds
99% <= 1006.68 milliseconds
99.9% <= 1006.68 milliseconds
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
645807 次 |
| 最近记录: |