java stopwatch 功能
C#中有一个stopwatch的功能,主要是用来监测程序执行时间的。java之前一直都在用如下方式完成:
public static void main(String[] args) {
long startTime=System.currentTimeMillis(); //获取开始时间
//函数主体代码
//...
long endTime=System.currentTimeMillis(); //获取结束时间
System.out.println("程序运行时间: "+(endTime-startTime)+"ms");
}
原生监测方式
今天上网搜索了一下,找到了一个比较类似的:
import org.apache.commons.lang3.time;
StopWatch watch=new StopWatch();
watch.start();
watch.stop();
watch.getSplitTime();
apache.commons.lang3
但是上面的时间处理只支持ms,有些时间比较长还得自己处理,就又找了一个:
import java.util.concurrent.TimeUnit;
import com.google.common.base.Stopwatch; Stopwatch watch = new Stopwatch();
watch.start();
watch.stop();
watch.elapsed(TimeUnit.MINUTES);
google stopwatch
时间可以支持多种格式,可以自由选择,但是看了下源码,感觉里面好多方法都是 @Deprecated,估计是比较老的api了:
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static java.util.concurrent.TimeUnit.MICROSECONDS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS; import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible; import java.util.concurrent.TimeUnit; /**
* An object that measures elapsed time in nanoseconds. It is useful to measure
* elapsed time using this class instead of direct calls to {@link
* System#nanoTime} for a few reasons:
*
* <ul>
* <li>An alternate time source can be substituted, for testing or performance
* reasons.
* <li>As documented by {@code nanoTime}, the value returned has no absolute
* meaning, and can only be interpreted as relative to another timestamp
* returned by {@code nanoTime} at a different time. {@code Stopwatch} is a
* more effective abstraction because it exposes only these relative values,
* not the absolute ones.
* </ul>
*
* <p>Basic usage:
* <pre>
* Stopwatch stopwatch = new Stopwatch().{@link #start start}();
* doSomething();
* stopwatch.{@link #stop stop}(); // optional
*
* long millis = stopwatch.elapsed(MILLISECONDS);
*
* log.info("that took: " + stopwatch); // formatted string like "12.3 ms"
* </pre>
*
* <p>Stopwatch methods are not idempotent; it is an error to start or stop a
* stopwatch that is already in the desired state.
*
* <p>When testing code that uses this class, use the {@linkplain
* #Stopwatch(Ticker) alternate constructor} to supply a fake or mock ticker.
* <!-- TODO(kevinb): restore the "such as" --> This allows you to
* simulate any valid behavior of the stopwatch.
*
* <p><b>Note:</b> This class is not thread-safe.
*
* @author Kevin Bourrillion
* @since 10.0
*/
@Beta
@GwtCompatible(emulated = true)
public final class Stopwatch {
private final Ticker ticker;
private boolean isRunning;
private long elapsedNanos;
private long startTick; /**
* Creates (but does not start) a new stopwatch using {@link System#nanoTime}
* as its time source.
*/
public Stopwatch() {
this(Ticker.systemTicker());
} /**
* Creates (but does not start) a new stopwatch, using the specified time
* source.
*/
public Stopwatch(Ticker ticker) {
this.ticker = checkNotNull(ticker, "ticker");
} /**
* Returns {@code true} if {@link #start()} has been called on this stopwatch,
* and {@link #stop()} has not been called since the last call to {@code
* start()}.
*/
public boolean isRunning() {
return isRunning;
} /**
* Starts the stopwatch.
*
* @return this {@code Stopwatch} instance
* @throws IllegalStateException if the stopwatch is already running.
*/
public Stopwatch start() {
checkState(!isRunning,
"This stopwatch is already running; it cannot be started more than once.");
isRunning = true;
startTick = ticker.read();
return this;
} /**
* Stops the stopwatch. Future reads will return the fixed duration that had
* elapsed up to this point.
*
* @return this {@code Stopwatch} instance
* @throws IllegalStateException if the stopwatch is already stopped.
*/
public Stopwatch stop() {
long tick = ticker.read();
checkState(isRunning,
"This stopwatch is already stopped; it cannot be stopped more than once.");
isRunning = false;
elapsedNanos += tick - startTick;
return this;
} /**
* Sets the elapsed time for this stopwatch to zero,
* and places it in a stopped state.
*
* @return this {@code Stopwatch} instance
*/
public Stopwatch reset() {
elapsedNanos = 0;
isRunning = false;
return this;
} private long elapsedNanos() {
return isRunning ? ticker.read() - startTick + elapsedNanos : elapsedNanos;
} /**
* Returns the current elapsed time shown on this stopwatch, expressed
* in the desired time unit, with any fraction rounded down.
*
* <p>Note that the overhead of measurement can be more than a microsecond, so
* it is generally not useful to specify {@link TimeUnit#NANOSECONDS}
* precision here.
*
* @since 14.0 (since 10.0 as {@code elapsedTime()})
*/
public long elapsed(TimeUnit desiredUnit) {
return desiredUnit.convert(elapsedNanos(), NANOSECONDS);
} /**
* Returns the current elapsed time shown on this stopwatch, expressed
* in the desired time unit, with any fraction rounded down.
*
* <p>Note that the overhead of measurement can be more than a microsecond, so
* it is generally not useful to specify {@link TimeUnit#NANOSECONDS}
* precision here.
*
* @deprecated Use {@link Stopwatch#elapsed(TimeUnit)} instead. This method is
* scheduled to be removed in Guava release 16.0.
*/
@Deprecated
public long elapsedTime(TimeUnit desiredUnit) {
return elapsed(desiredUnit);
} /**
* Returns the current elapsed time shown on this stopwatch, expressed
* in milliseconds, with any fraction rounded down. This is identical to
* {@code elapsed(TimeUnit.MILLISECONDS)}.
*
* @deprecated Use {@code stopwatch.elapsed(MILLISECONDS)} instead. This
* method is scheduled to be removed in Guava release 16.0.
*/
@Deprecated
public long elapsedMillis() {
return elapsed(MILLISECONDS);
} /**
* Returns a string representation of the current elapsed time.
*/
@GwtIncompatible("String.format()")
@Override public String toString() {
return toString(4);
} /**
* Returns a string representation of the current elapsed time, choosing an
* appropriate unit and using the specified number of significant figures.
* For example, at the instant when {@code elapsed(NANOSECONDS)} would
* return {1234567}, {@code toString(4)} returns {@code "1.235 ms"}.
*
* @deprecated Use {@link #toString()} instead. This method is scheduled
* to be removed in Guava release 15.0.
*/
@Deprecated
@GwtIncompatible("String.format()")
public String toString(int significantDigits) {
long nanos = elapsedNanos(); TimeUnit unit = chooseUnit(nanos);
double value = (double) nanos / NANOSECONDS.convert(1, unit); // Too bad this functionality is not exposed as a regular method call
return String.format("%." + significantDigits + "g %s",
value, abbreviate(unit));
} private static TimeUnit chooseUnit(long nanos) {
if (SECONDS.convert(nanos, NANOSECONDS) > 0) {
return SECONDS;
}
if (MILLISECONDS.convert(nanos, NANOSECONDS) > 0) {
return MILLISECONDS;
}
if (MICROSECONDS.convert(nanos, NANOSECONDS) > 0) {
return MICROSECONDS;
}
return NANOSECONDS;
} private static String abbreviate(TimeUnit unit) {
switch (unit) {
case NANOSECONDS:
return "ns";
case MICROSECONDS:
return "\u03bcs"; // 渭s
case MILLISECONDS:
return "ms";
case SECONDS:
return "s";
default:
throw new AssertionError();
}
}
}
google stopwatch source code
java stopwatch 功能的更多相关文章
- JAVA文件下载功能问题解决日志
今天给报告系统做了个下载功能,遇到了挺多问题,通过查资料一一解决了. 1.首先遇到的问题是:java后台的输出流输出之后,没有任何报错,浏览器端不弹出保存文件的对话框,原本是ajax请求到后台的con ...
- python面向对象进阶 反射 单例模式 以及python实现类似java接口功能
本篇将详细介绍Python 类的成员.成员修饰符.类的特殊成员. 类的成员 类的成员可以分为三大类:字段.方法和特性. 注:所有成员中,只有普通字段的内容保存对象中,即:根据此类创建了多少对象,在内存 ...
- Atitit.java eval功能的实现 Compiler API
Atitit.java eval功能的实现 Compiler API 输出echo2 输出目录配置2 针对编译器,JDK 设计了两个接口,分别是 JavaCompiler 和JavaCompiler ...
- Android 虚拟机Dalvik、Android各种java包功能、Android相关文件类型、应用程序结构分析、ADB
Android虚拟机Dalvik Dalvik冲击 随着Google 的AndroidSDK 的发布,关于它的API 以及在移动电话领域所带来的预期影响这些方面的讨论不胜枚举.不过,其中的一个话题在J ...
- JNI的替代者—使用JNA访问Java外部功能接口
摘自:http://www.cnblogs.com/lanxuezaipiao/p/3635556.html JNI的替代者-使用JNA访问Java外部功能接口 1. JNA简单介绍 先说JNI(Ja ...
- 【C/C++开发】【Java开发】JNI的替代者—使用JNA访问Java外部功能接口
JNI的替代者-使用JNA访问Java外部功能接口 1. JNA简单介绍 先说JNI(Java Native Interface)吧,有过不同语言间通信经历的一般都知道,它允许Java代码和其他语言( ...
- Java订单功能模块设计与实现
在商城项目中,之前我们介绍了购物车功能模块的实现,商品加入到购物车之后,就是到购物车结算,然后显示购物车的商品列表,点击去结算,然后到了未提交前的订单列表, 点击提交订单后,生成此订单,返回订单的订单 ...
- JAVA 上传图片功能
前后端实现上传图片功能(JAVA代码) 1.前端大概 请求头必须为AJAX请求头: 'X-Requested-With': 'XMLHttpRequest' 一般是指网页中存在的Content-Typ ...
- Java实现功能简单的学生管理系统(附带源代码)
这几天Java学了点新的知识,打算要用这些知识做一个比较简单的管理系统,实战一下子,代码中的功能简洁,可能不多,但是作为一个练手来了解一个项目是怎么样一点一点思考的还是不错的 一.代码中要实现的功能 ...
随机推荐
- Drools 函数学习
Drools 函数学习 函数是定义在规则文件当中一代码块,作用是将在规则文件当中若干个规则都会用到的业务操作封装起来,实现业务代码的复用,减少规则编写的工作量.函数的编写位置可以是规则文件当中 pac ...
- -webkit-tap-highlight-color
css3中有henduo 新属性,tap-highlight-color;是用于元素在移动设备IOS和adnroid上被触发点击事件时,响应的背景框的颜色. 例如在Adnroid版本的微信中,点击a标 ...
- EventLoop和EventLoopGroup
Netty框架的主要线程就是I/O线程,线程模型设计的好坏,决定了系统的吞吐量.并发性和安全性等架构质量属性.Netty的线程模型被精心地设计,既提升了框架的并发性能,又能在很大程度避免锁,局部实现了 ...
- linux菜鸟日记
本地yum源的安装: 要安装本地yum源,首先需要熟悉本地yum文件的配置和光盘的挂载 第一步挂载光盘: 首先需要指定一个光盘挂载目录 通常情况下我习惯使用默认挂载目录,所以一般我使用的光盘挂载命令是 ...
- init shutdown reboot poweroff halt区别
init 首先看看LINUX系统几种运行级别# 0 - 停机(千万别把initdefault设置为0,否则系统永远无法启动)# 1 - 单用户模式# 2 - 多用户,没有 NFS# 3 - 完全多用户 ...
- js前端模块化之加载器原理解析(一)
先来说一下前端模块化的价值:引用模块此处有详细的介绍,可以自行前往观看. 一.总结如下优点: (1)解决命名冲突(2)烦琐的文件依赖(3)模块的版本管理(4)提高可维护性(5)前端性能优化(6)跨环境 ...
- QGis、Qt对话框上的OK、Open、Cancel、Help等英文翻译
成功编译qgis,启动程序发现对话框上的OK.Open.Cancel.Help等依然是英文字段,然后查找源码看这些字段是否都添加到了语言翻译包中: 最后发现这些按钮都是qt的QTGui4库中的QDia ...
- 关于click和submit的笔记
click主要用于元素的点击时的响应事件,而submit是指表单元素form的提交事件. 但是,当click加入到表单的提交按钮时,事情似乎就有点复杂,总是忘记了.这两天搜了下,又实践了一下. 主要用 ...
- Excel Sheet Column Title
Given a positive integer, return its corresponding column title as appear in an Excel sheet. For exa ...
- Python之路Day16--JavaScript(二)
本节内容: 1.上节内容回顾 2.JavaScript补充 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 一.上节内容回顾 1.作业问题: a.页面布局不好 ...