java stopwatch 功能

C#中有一个stopwatch的功能,主要是用来监测程序执行时间的。java之前一直都在用如下方式完成:

 1     public static void main(String[] args) {
 2         long startTime=System.currentTimeMillis();   //获取开始时间
 3
 4         //函数主体代码
 5         //...
 6
 7         long endTime=System.currentTimeMillis(); //获取结束时间
 8         System.out.println("程序运行时间: "+(endTime-startTime)+"ms");
 9
10     }

原生监测方式

今天上网搜索了一下,找到了一个比较类似的:

1 import org.apache.commons.lang3.time;
2
3         StopWatch watch=new  StopWatch();
4         watch.start();
5         watch.stop();
6         watch.getSplitTime();    

apache.commons.lang3

但是上面的时间处理只支持ms,有些时间比较长还得自己处理,就又找了一个:

1 import java.util.concurrent.TimeUnit;
2 import com.google.common.base.Stopwatch;
3
4         Stopwatch watch = new Stopwatch();
5         watch.start();
6         watch.stop();
7         watch.elapsed(TimeUnit.MINUTES);

google stopwatch

时间可以支持多种格式,可以自由选择,但是看了下源码,感觉里面好多方法都是  @Deprecated,估计是比较老的api了:

  1 /*
  2  * Copyright (C) 2008 The Guava Authors
  3  *
  4  * Licensed under the Apache License, Version 2.0 (the "License");
  5  * you may not use this file except in compliance with the License.
  6  * You may obtain a copy of the License at
  7  *
  8  * http://www.apache.org/licenses/LICENSE-2.0
  9  *
 10  * Unless required by applicable law or agreed to in writing, software
 11  * distributed under the License is distributed on an "AS IS" BASIS,
 12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  * See the License for the specific language governing permissions and
 14  * limitations under the License.
 15  */
 16
 17 package com.google.common.base;
 18
 19 import static com.google.common.base.Preconditions.checkNotNull;
 20 import static com.google.common.base.Preconditions.checkState;
 21 import static java.util.concurrent.TimeUnit.MICROSECONDS;
 22 import static java.util.concurrent.TimeUnit.MILLISECONDS;
 23 import static java.util.concurrent.TimeUnit.NANOSECONDS;
 24 import static java.util.concurrent.TimeUnit.SECONDS;
 25
 26 import com.google.common.annotations.Beta;
 27 import com.google.common.annotations.GwtCompatible;
 28 import com.google.common.annotations.GwtIncompatible;
 29
 30 import java.util.concurrent.TimeUnit;
 31
 32 /**
 33  * An object that measures elapsed time in nanoseconds. It is useful to measure
 34  * elapsed time using this class instead of direct calls to {@link
 35  * System#nanoTime} for a few reasons:
 36  *
 37  * <ul>
 38  * <li>An alternate time source can be substituted, for testing or performance
 39  *     reasons.
 40  * <li>As documented by {@code nanoTime}, the value returned has no absolute
 41  *     meaning, and can only be interpreted as relative to another timestamp
 42  *     returned by {@code nanoTime} at a different time. {@code Stopwatch} is a
 43  *     more effective abstraction because it exposes only these relative values,
 44  *     not the absolute ones.
 45  * </ul>
 46  *
 47  * <p>Basic usage:
 48  * <pre>
 49  *   Stopwatch stopwatch = new Stopwatch().{@link #start start}();
 50  *   doSomething();
 51  *   stopwatch.{@link #stop stop}(); // optional
 52  *
 53  *   long millis = stopwatch.elapsed(MILLISECONDS);
 54  *
 55  *   log.info("that took: " + stopwatch); // formatted string like "12.3 ms"
 56  * </pre>
 57  *
 58  * <p>Stopwatch methods are not idempotent; it is an error to start or stop a
 59  * stopwatch that is already in the desired state.
 60  *
 61  * <p>When testing code that uses this class, use the {@linkplain
 62  * #Stopwatch(Ticker) alternate constructor} to supply a fake or mock ticker.
 63  * <!-- TODO(kevinb): restore the "such as" --> This allows you to
 64  * simulate any valid behavior of the stopwatch.
 65  *
 66  * <p><b>Note:</b> This class is not thread-safe.
 67  *
 68  * @author Kevin Bourrillion
 69  * @since 10.0
 70  */
 71 @Beta
 72 @GwtCompatible(emulated = true)
 73 public final class Stopwatch {
 74   private final Ticker ticker;
 75   private boolean isRunning;
 76   private long elapsedNanos;
 77   private long startTick;
 78
 79   /**
 80    * Creates (but does not start) a new stopwatch using {@link System#nanoTime}
 81    * as its time source.
 82    */
 83   public Stopwatch() {
 84     this(Ticker.systemTicker());
 85   }
 86
 87   /**
 88    * Creates (but does not start) a new stopwatch, using the specified time
 89    * source.
 90    */
 91   public Stopwatch(Ticker ticker) {
 92     this.ticker = checkNotNull(ticker, "ticker");
 93   }
 94
 95   /**
 96    * Returns {@code true} if {@link #start()} has been called on this stopwatch,
 97    * and {@link #stop()} has not been called since the last call to {@code
 98    * start()}.
 99    */
100   public boolean isRunning() {
101     return isRunning;
102   }
103
104   /**
105    * Starts the stopwatch.
106    *
107    * @return this {@code Stopwatch} instance
108    * @throws IllegalStateException if the stopwatch is already running.
109    */
110   public Stopwatch start() {
111     checkState(!isRunning,
112         "This stopwatch is already running; it cannot be started more than once.");
113     isRunning = true;
114     startTick = ticker.read();
115     return this;
116   }
117
118   /**
119    * Stops the stopwatch. Future reads will return the fixed duration that had
120    * elapsed up to this point.
121    *
122    * @return this {@code Stopwatch} instance
123    * @throws IllegalStateException if the stopwatch is already stopped.
124    */
125   public Stopwatch stop() {
126     long tick = ticker.read();
127     checkState(isRunning,
128         "This stopwatch is already stopped; it cannot be stopped more than once.");
129     isRunning = false;
130     elapsedNanos += tick - startTick;
131     return this;
132   }
133
134   /**
135    * Sets the elapsed time for this stopwatch to zero,
136    * and places it in a stopped state.
137    *
138    * @return this {@code Stopwatch} instance
139    */
140   public Stopwatch reset() {
141     elapsedNanos = 0;
142     isRunning = false;
143     return this;
144   }
145
146   private long elapsedNanos() {
147     return isRunning ? ticker.read() - startTick + elapsedNanos : elapsedNanos;
148   }
149
150   /**
151    * Returns the current elapsed time shown on this stopwatch, expressed
152    * in the desired time unit, with any fraction rounded down.
153    *
154    * <p>Note that the overhead of measurement can be more than a microsecond, so
155    * it is generally not useful to specify {@link TimeUnit#NANOSECONDS}
156    * precision here.
157    *
158    * @since 14.0 (since 10.0 as {@code elapsedTime()})
159    */
160   public long elapsed(TimeUnit desiredUnit) {
161     return desiredUnit.convert(elapsedNanos(), NANOSECONDS);
162   }
163
164   /**
165    * Returns the current elapsed time shown on this stopwatch, expressed
166    * in the desired time unit, with any fraction rounded down.
167    *
168    * <p>Note that the overhead of measurement can be more than a microsecond, so
169    * it is generally not useful to specify {@link TimeUnit#NANOSECONDS}
170    * precision here.
171    *
172    * @deprecated Use {@link Stopwatch#elapsed(TimeUnit)} instead. This method is
173    *     scheduled to be removed in Guava release 16.0.
174    */
175   @Deprecated
176   public long elapsedTime(TimeUnit desiredUnit) {
177     return elapsed(desiredUnit);
178   }
179
180   /**
181    * Returns the current elapsed time shown on this stopwatch, expressed
182    * in milliseconds, with any fraction rounded down. This is identical to
183    * {@code elapsed(TimeUnit.MILLISECONDS)}.
184    *
185    * @deprecated Use {@code stopwatch.elapsed(MILLISECONDS)} instead. This
186    *     method is scheduled to be removed in Guava release 16.0.
187    */
188   @Deprecated
189   public long elapsedMillis() {
190     return elapsed(MILLISECONDS);
191   }
192
193   /**
194    * Returns a string representation of the current elapsed time.
195    */
196   @GwtIncompatible("String.format()")
197   @Override public String toString() {
198     return toString(4);
199   }
200
201   /**
202    * Returns a string representation of the current elapsed time, choosing an
203    * appropriate unit and using the specified number of significant figures.
204    * For example, at the instant when {@code elapsed(NANOSECONDS)} would
205    * return {1234567}, {@code toString(4)} returns {@code "1.235 ms"}.
206    *
207    * @deprecated Use {@link #toString()} instead. This method is scheduled
208    *     to be removed in Guava release 15.0.
209    */
210   @Deprecated
211   @GwtIncompatible("String.format()")
212   public String toString(int significantDigits) {
213     long nanos = elapsedNanos();
214
215     TimeUnit unit = chooseUnit(nanos);
216     double value = (double) nanos / NANOSECONDS.convert(1, unit);
217
218     // Too bad this functionality is not exposed as a regular method call
219     return String.format("%." + significantDigits + "g %s",
220         value, abbreviate(unit));
221   }
222
223   private static TimeUnit chooseUnit(long nanos) {
224     if (SECONDS.convert(nanos, NANOSECONDS) > 0) {
225       return SECONDS;
226     }
227     if (MILLISECONDS.convert(nanos, NANOSECONDS) > 0) {
228       return MILLISECONDS;
229     }
230     if (MICROSECONDS.convert(nanos, NANOSECONDS) > 0) {
231       return MICROSECONDS;
232     }
233     return NANOSECONDS;
234   }
235
236   private static String abbreviate(TimeUnit unit) {
237     switch (unit) {
238       case NANOSECONDS:
239         return "ns";
240       case MICROSECONDS:
241         return "\u03bcs"; // 渭s
242       case MILLISECONDS:
243         return "ms";
244       case SECONDS:
245         return "s";
246       default:
247         throw new AssertionError();
248     }
249   }
250 }

google stopwatch source code

  

时间: 2024-08-10 01:55:45

java stopwatch 功能的相关文章

JAVA文件下载功能问题解决日志

今天给报告系统做了个下载功能,遇到了挺多问题,通过查资料一一解决了. 1.首先遇到的问题是:java后台的输出流输出之后,没有任何报错,浏览器端不弹出保存文件的对话框,原本是ajax请求到后台的controller方法中添加了下载的方法,type和async两个参数的四种组合都不行,弃用ajax,用window.location.href='file/download?path='+file;重新发一个新的下载请求之后,保存对话框终于弹出. 2.弹出之后,发现文件名乱码,后台的解决方案代码如下:

Atitit.java eval功能的实现 &#160;Compiler API

Atitit.java eval功能的实现  Compiler API 输出echo2 输出目录配置2 针对编译器,JDK 设计了两个接口,分别是 JavaCompiler 和JavaCompiler.CompilationTask. private static void T() throws FileNotFoundException { //String fullQuanlifiedFileName = "compile" + java.io.File.separator + /

java签到功能

原文:java签到功能 源代码下载地址:http://www.zuidaima.com/share/1550463784176640.htm spring+springMVC+hibernate框架 简单的登陆验证 签到的主要处理在于签到历史的显示 测试账号test 密码test 插件路径在readme里 截图:    

Java 正则表达式功能及应用

正则表达式,就是用某种模式去匹配一类字符串的一个公式,正则表达式由一些普通字符和一些元字符(metacharacters)组成.普通字符包括大小写的字母和数字,而元字符则具有特殊的含义,不管是.Net平台还是Java平台,正则表达式表达的意思都是一样的,下面我们主要分析Java正则表达式中的功能和具体应用,希望文章对您有所帮助,仅供参考. 自从jdk1.4推出java.util.regex包,就为我们提供了很好的Java正则表达式应用平台,因为Java正则表达式是一个很庞杂的体系. \\ 反斜杠

java分页功能代码

import java.util.ArrayList; import java.util.List; /** * * @author cheney * * @date Aug 31, 2012 */ public class PageModel<T> { private int page = 1; // 当前页 public int totalPages = 0; // 总页数 private int pageRecorders;// 每页5条数据 private int totalRows

delphi android 录像(调用Java的功能)

delphi xe系列自带的控件都无法保存录像,经网友帮忙,昨天终于实现了录像功能(但有个问题是录像时无画面显示),程序主要使用了JMediaRecorder,MediaRecorder的使用方法可参考网上java的相关说明,下面代码是可以正常录像的: unit Unit8; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, Androidapi.Helpe

java读写 功能

/*字符流:Reader Writer. 需求:在硬盘上创建一个文件并写入一些数据.*/import java.io.*; /*//创建FileWriter对象,调用window资源,在指定位置创建好了数据存放的目的地.        //如果指定目录下,已存在要创建的文件,那么会被覆盖. FileWriter fw = new FileWriter("demo.txt"); //通过流对象write方法将字符串写入到流中.        fw.write("abcde&qu

#python+java#同样功能的代码两种语言实现

概述:设置两个数组/列表,列表a是[1,2,3],列表b是['a','b','c'],把他们一对一对打印出来,但不打印"3:c"这对. python版: ''' Created on 2014-11-2 @author: Administrator ''' class MyArray:     def __init__(self):         self.a = range(1,4)         self.b = ['a','b','c']     def getValue(s

Java 文件下载功能 解决中文乱码

Html部分 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <a href="http://localhost:8080/webdemojava/download1?filename=a.flv" class=&