Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >java stopwatch_java stopwatch 功能

java stopwatch_java stopwatch 功能

作者头像
全栈程序员站长
发布于 2022-09-09 13:20:54
发布于 2022-09-09 13:20:54
41100
代码可运行
举报
运行总次数:0
代码可运行

大家好,又见面了,我是你们的朋友全栈君。

1 /*

2 * Copyright (C) 2008 The Guava Authors3 *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 at7 *8 *http://www.apache.org/licenses/LICENSE-2.0

9 *10 * Unless required by applicable law or agreed to in writing, software11 * 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 and14 * limitations under the License.15 */

16

17 packagecom.google.common.base;18

19 import staticcom.google.common.base.Preconditions.checkNotNull;20 import staticcom.google.common.base.Preconditions.checkState;21 import staticjava.util.concurrent.TimeUnit.MICROSECONDS;22 import staticjava.util.concurrent.TimeUnit.MILLISECONDS;23 import staticjava.util.concurrent.TimeUnit.NANOSECONDS;24 import staticjava.util.concurrent.TimeUnit.SECONDS;25

26 importcom.google.common.annotations.Beta;27 importcom.google.common.annotations.GwtCompatible;28 importcom.google.common.annotations.GwtIncompatible;29

30 importjava.util.concurrent.TimeUnit;31

32 /**

33 * An object that measures elapsed time in nanoseconds. It is useful to measure34 * elapsed time using this class instead of direct calls to {@link

35 * System#nanoTime} for a few reasons:36 *37 *

  • 38 *
  • An alternate time source can be substituted, for testing or performance39 * reasons.40 *
  • As documented by {@codenanoTime}, the value returned has no absolute41 * meaning, and can only be interpreted as relative to another timestamp42 * returned by {@codenanoTime} at a different time. {@codeStopwatch} is a43 * more effective abstraction because it exposes only these relative values,44 * not the absolute ones.45 *

46 *47 *

Basic usage:48 *

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
49 *   Stopwatch stopwatch = new Stopwatch().{@link#start start}();50 *   doSomething();51 *   stopwatch.{@link#stop stop}(); // optional52 *53 *   long millis = stopwatch.elapsed(MILLISECONDS);54 *55 *   log.info("that took: " + stopwatch); // formatted string like "12.3 ms"56 * 

57 *58 *

Stopwatch methods are not idempotent; it is an error to start or stop a59 * stopwatch that is already in the desired state.60 *61 *

When testing code that uses this class, use the {@linkplain

62 * #Stopwatch(Ticker) alternate constructor} to supply a fake or mock ticker.63 * This allows you to64 * simulate any valid behavior of the stopwatch.65 *66 *

Note: This class is not thread-safe.67 *68 *@authorKevin Bourrillion69 *@since10.070 */

71 @Beta72 @GwtCompatible(emulated = true)73 public final classStopwatch {74 private finalTicker ticker;75 private booleanisRunning;76 private longelapsedNanos;77 private longstartTick;78

79 /**

80 * Creates (but does not start) a new stopwatch using {@linkSystem#nanoTime}81 * as its time source.82 */

83 publicStopwatch() {84 this(Ticker.systemTicker());85 }86

87 /**

88 * Creates (but does not start) a new stopwatch, using the specified time89 * source.90 */

91 publicStopwatch(Ticker ticker) {92 this.ticker = checkNotNull(ticker, “ticker”);93 }94

95 /**

96 * Returns {@codetrue} 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 booleanisRunning() {101 returnisRunning;102 }103

104 /**

105 * Starts the stopwatch.106 *107 *@returnthis {@codeStopwatch} instance108 *@throwsIllegalStateException if the stopwatch is already running.109 */

110 publicStopwatch 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 had120 * elapsed up to this point.121 *122 *@returnthis {@codeStopwatch} instance123 *@throwsIllegalStateException if the stopwatch is already stopped.124 */

125 publicStopwatch 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 *@returnthis {@codeStopwatch} instance139 */

140 publicStopwatch reset() {141 elapsedNanos = 0;142 isRunning = false;143 return this;144 }145

146 private longelapsedNanos() {147 return isRunning ? ticker.read() – startTick +elapsedNanos : elapsedNanos;148 }149

150 /**

151 * Returns the current elapsed time shown on this stopwatch, expressed152 * in the desired time unit, with any fraction rounded down.153 *154 *

Note that the overhead of measurement can be more than a microsecond, so155 * it is generally not useful to specify {@linkTimeUnit#NANOSECONDS}156 * precision here.157 *158 *@since14.0 (since 10.0 as {@codeelapsedTime()})159 */

160 public longelapsed(TimeUnit desiredUnit) {161 returndesiredUnit.convert(elapsedNanos(), NANOSECONDS);162 }163

164 /**

165 * Returns the current elapsed time shown on this stopwatch, expressed166 * in the desired time unit, with any fraction rounded down.167 *168 *

Note that the overhead of measurement can be more than a microsecond, so169 * it is generally not useful to specify {@linkTimeUnit#NANOSECONDS}170 * precision here.171 *172 *@deprecatedUse {@linkStopwatch#elapsed(TimeUnit)} instead. This method is173 * scheduled to be removed in Guava release 16.0.174 */

175 @Deprecated176 public longelapsedTime(TimeUnit desiredUnit) {177 returnelapsed(desiredUnit);178 }179

180 /**

181 * Returns the current elapsed time shown on this stopwatch, expressed182 * in milliseconds, with any fraction rounded down. This is identical to183 * {@codeelapsed(TimeUnit.MILLISECONDS)}.184 *185 *@deprecatedUse {@codestopwatch.elapsed(MILLISECONDS)} instead. This186 * method is scheduled to be removed in Guava release 16.0.187 */

188 @Deprecated189 public longelapsedMillis() {190 returnelapsed(MILLISECONDS);191 }192

193 /**

194 * Returns a string representation of the current elapsed time.195 */

196 @GwtIncompatible(“String.format()”)197 @Override publicString toString() {198 return toString(4);199 }200

201 /**

202 * Returns a string representation of the current elapsed time, choosing an203 * appropriate unit and using the specified number of significant figures.204 * For example, at the instant when {@codeelapsed(NANOSECONDS)} would205 * return {1234567}, {@codetoString(4)} returns {@code”1.235 ms”}.206 *207 *@deprecatedUse {@link#toString()} instead. This method is scheduled208 * to be removed in Guava release 15.0.209 */

210 @Deprecated211 @GwtIncompatible(“String.format()”)212 public String toString(intsignificantDigits) {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(longnanos) {224 if (SECONDS.convert(nanos, NANOSECONDS) > 0) {225 returnSECONDS;226 }227 if (MILLISECONDS.convert(nanos, NANOSECONDS) > 0) {228 returnMILLISECONDS;229 }230 if (MICROSECONDS.convert(nanos, NANOSECONDS) > 0) {231 returnMICROSECONDS;232 }233 returnNANOSECONDS;234 }235

236 private staticString abbreviate(TimeUnit unit) {237 switch(unit) {238 caseNANOSECONDS:239 return “ns”;240 caseMICROSECONDS:241 return “\u03bcs”; //渭s

242 caseMILLISECONDS:243 return “ms”;244 caseSECONDS:245 return “s”;246 default:247 throw newAssertionError();248 }249 }250 }

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/152456.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
Guava 中的 Stopwatch 是个什么鬼?
看了上面这段代码,有人会说,不用Stopwatch 照样可以实现执行时间的统计,比如:
程序猿DD
2020/10/27
1.3K0
Guava 中的 Stopwatch 是个什么鬼?
6种快速统计代码执行时间的方法,真香!(史上最全)
我们在日常开发中经常需要测试一些代码的执行时间,但又不想使用向 JMH(Java Microbenchmark Harness,Java 微基准测试套件)这么重的测试框架,所以本文就汇总了一些 Java 中比较常用的执行时间统计方法,总共包含以下 6 种,如下图所示:
用户6256742
2024/05/16
5530
6种快速统计代码执行时间的方法,真香!(史上最全)
6种快速统计代码执行时间的方法,真香!
我们在日常开发中经常需要测试一些代码的执行时间,但又不想使用向 JMH(Java Microbenchmark Harness,Java 微基准测试套件)这么重的测试框架,所以本文就汇总了一些 Java 中比较常用的执行时间统计方法,总共包含以下 6 种,如下图所示:
磊哥
2020/07/15
1.6K0
6种快速统计代码执行时间的方法,真香!
Guava之Stopwatch「建议收藏」
Stopwatch用来计算经过的时间(精确到纳秒)。 这个类比调用System.nanoTime()优势在于:
全栈程序员站长
2022/09/09
2.7K0
Guava-1.21 类StopWatch
用来计算经过的时间(精确到纳秒)。 这个类比调用System.nanoTime()优势在于:
悠扬前奏
2019/05/30
1.3K0
学习stopwatch
处理过程(学习stopwatch) 虽然debug可以查看到每一步代码执行时发生的变化,但是不能清楚的看到每一步执行的时间,这个时候Stopwatch就派上用场了。 什么是stopwatch? Stopwatch是Guava(Google开源java库)中推出的计时器类,可以用于方便的检测两个代码直接执行的速度 Stopwatch简单用法
全栈程序员站长
2022/09/07
4620
聊聊Guava的RateLimiter
guava-26.0-jre-sources.jar!/com/google/common/util/concurrent/RateLimiter.java
code4it
2018/09/17
2.8K0
java 中stopwatch,Stopwatch
* An object that accurately measures elapsed time: the measured duration between two
全栈程序员站长
2022/09/10
4320
Apache Kylin-2.6安装部署
构建过程是一个MapReduce任务,比较耗时,构建之前确保MapReduce History Server是启动的,否则会报错
CoderJed
2021/04/13
1.1K1
Java 中 Future 的 get 方法超时会怎样?
很多 Java 工程师在准备面试时,会刷很多八股文,线程和线程池这一块通常会准备线程的状态、线程的创建方式,Executors 里面的一些工厂方法和为什么不推荐使用这些工厂方法,ThreadPoolExecutor 构造方法的一些参数和执行过程等。
明明如月学长
2022/06/15
4.2K0
Java 中 Future 的 get 方法超时会怎样?
futureTask的超时原理解析
java/util/concurrent/AbstractExecutorService.java
code4it
2018/09/17
8500
【小家java】Apache Commons-lang3提供的StopWatch执行时间监视器,以及Spring提供的StopWatch分析
编码过程中我们经常会希望得到一段代码(一个方法)的执行时间,本文将介绍两种时间监视器(秒表)来让你优雅的、灵活的处理这个问题。
YourBatman
2019/09/03
4.6K0
通过java.util.concurrent.TimeUnit来学习枚举
今天无意间看到了java.util.concurrent.TimeUnit枚举类。
明明如月学长
2021/08/31
5180
通过java.util.concurrent.TimeUnit来学习枚举
GuavaCache学习笔记三:底层源码阅读
申明:转载自 https://www.cnblogs.com/dennyzhangdd/p/8981982.html
一枝花算不算浪漫
2018/12/25
1.1K0
使用StopWatch计算耗时[通俗易懂]
一般采用 System.currentTimeMillis() 来获取时间,然后打印当前时间与任务开始执行时间的差值。
全栈程序员站长
2022/09/09
1.7K0
使用StopWatch计算耗时[通俗易懂]
Java Review - 并发编程_DelayQueue原理&源码剖析
DelayQueue并发队列是一个无界阻塞延迟队列,队列中的每个元素都有个过期时间,当从队列获取元素时,只有过期元素才会出队列。
小小工匠
2021/12/30
4110
Java Review - 并发编程_DelayQueue原理&源码剖析
Stopwatch类学习
1、概述:给一条大MSDN的链接关于Stopwatch类最详细的教程 ,然后看着教程自己手动敲一边,加深映象,好记性不如烂键盘,哈哈,开个玩笑! 2、类位置:这个类在哪里,这个是重点,虽然C#IDE很强大,但是我们还是得简单的了解下。通过一段代码来说明: using System; namespace System.Diagnostics{     public class Stopwatch:System.Object    {    } } 是不是一目了然! 3、类属性介绍 下面是Stopwatch类
郑小超.
2018/01/24
5650
Stopwatch类学习
并行执行任务
在app列表首页,展示多个item,并有分页;而每个item里后台都会调用一个http请求,判断当前item的状态
LiosWong
2018/10/29
7440
Springframwork.Util之StopWatch 多任务计时
StopWatch是spring框架提供的一个util, 用来做多任务的计时, 隐藏了System.currentTimeMillis()的使用, 增加应用程序的可读性, 但是他不是为线程安全来设计的
CoffeeLand
2020/04/06
2K0
多线程基础(十):LockSupport源码及其使用
在前面学习过java线程间通信的几种方式,分别是synchronized结合wait/notify。以及ReentrantLock结合Condation的await和signal方法。那么实际上还有一种方法也能实现线程通信,那就是LockSupport。我们来看看其源码。
冬天里的懒猫
2020/09/16
4160
相关推荐
Guava 中的 Stopwatch 是个什么鬼?
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验