本文整理了Java中com.google.common.base.Stopwatch
类的一些代码示例,展示了Stopwatch
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Stopwatch
类的具体详情如下:
包路径:com.google.common.base.Stopwatch
类名称:Stopwatch
[英]An object that measures elapsed time in nanoseconds. It is useful to measure elapsed time using this class instead of direct calls to System#nanoTime for a few reasons:
Basic usage:
Stopwatch stopwatch = Stopwatch.
#createStarted();
doSomething();
stopwatch.
#stop(); // optional
long millis = stopwatch.elapsed(MILLISECONDS);
log.info("time: " + stopwatch); // formatted string like "12.3 ms"
Stopwatch methods are not idempotent; it is an error to start or stop a stopwatch that is already in the desired state.
When testing code that uses this class, use #createUnstarted(Ticker) or #createStarted(Ticker) to supply a fake or mock ticker. This allows you to simulate any valid behavior of the stopwatch.
Note: This class is not thread-safe.
[中]以纳秒为单位测量经过时间的物体。使用此类来测量运行时间,而不是直接调用System#nanoTime,这很有用,原因如下:
*出于测试或性能原因,可以使用替代时间源。
*正如nanoTime所记录的,返回的值没有绝对意义,只能解释为相对于nanoTime在不同时间返回的另一个时间戳。秒表是一种更有效的抽象,因为它只显示这些相对值,而不是绝对值。
基本用法:
Stopwatch stopwatch = Stopwatch.
#createStarted();
doSomething();
stopwatch.
#stop(); // optional
long millis = stopwatch.elapsed(MILLISECONDS);
log.info("time: " + stopwatch); // formatted string like "12.3 ms"
秒表方法不是幂等的;启动或停止已处于所需状态的秒表是错误的。
测试使用此类的代码时,请使用#createUnstarted(Ticker)或#createStarted(Ticker)提供虚假或模拟的Ticker。这允许您模拟秒表的任何有效行为。
注意:这个类不是线程安全的。
代码示例来源:origin: apache/incubator-druid
@Override
public void persist(final Committer committer)
{
final Stopwatch runExecStopwatch = Stopwatch.createStarted();
appenderator.persistAll(committer);
final long startDelay = runExecStopwatch.elapsed(TimeUnit.MILLISECONDS);
metrics.incrementPersistBackPressureMillis(startDelay);
if (startDelay > WARN_DELAY) {
log.warn("Ingestion was throttled for [%,d] millis because persists were pending.", startDelay);
}
runExecStopwatch.stop();
}
代码示例来源:origin: apache/incubator-gobblin
private void createNewLogFileIfNeeded() throws IOException {
if (LogCopier.this.destFs.exists(this.destLogFile)
&& (this.watch.elapsed(TimeUnit.MINUTES) > LogCopier.this.maxMinutesPerLogFile
|| LogCopier.this.destFs.getFileStatus(this.destLogFile).getLen() > LogCopier.this.maxBytesPerLogFile)) {
HadoopUtils.renamePath(LogCopier.this.destFs, this.destLogFile,
new Path(this.destLogFile.toString() + "." + System.currentTimeMillis()));
this.watch.reset();
this.watch.start();
}
}
代码示例来源:origin: google/guava
/**
* Creates (and starts) a new stopwatch, using the specified time source.
*
* @since 15.0
*/
public static Stopwatch createStarted(Ticker ticker) {
return new Stopwatch(ticker).start();
}
代码示例来源:origin: stackoverflow.com
class TimeTest2 {
public static void main(String[] args) {
Stopwatch timer = new Stopwatch().start();
long total = 0;
for (int i = 0; i < 10000000; i++) {
total += i;
}
timer.stop();
System.out.println(timer.getElapsedTime());
}
}
代码示例来源:origin: twitter/distributedlog
public AbstractStreamOp(String stream,
OpStatsLogger statsLogger,
Long checksum,
Feature checksumDisabledFeature) {
this.stream = stream;
this.opStatsLogger = statsLogger;
// start here in case the operation is failed before executing.
stopwatch.reset().start();
this.checksum = checksum;
this.checksumDisabledFeature = checksumDisabledFeature;
}
代码示例来源:origin: google/guava
private void assertUninterruptibleDrained(BlockingQueue<Object> q) {
assertEquals(0, Queues.drainUninterruptibly(q, ImmutableList.of(), 0, 10, MILLISECONDS));
// but does the wait actually occurs?
@SuppressWarnings("unused") // go/futurereturn-lsc
Future<?> possiblyIgnoredError = threadPool.submit(new Interrupter(currentThread()));
Stopwatch timer = Stopwatch.createStarted();
Queues.drainUninterruptibly(q, newArrayList(), 1, 10, MILLISECONDS);
assertThat(timer.elapsed(MILLISECONDS)).isAtLeast(10L);
// wait for interrupted status and clear it
while (!Thread.interrupted()) {
Thread.yield();
}
}
代码示例来源:origin: apache/incubator-druid
throw new ISE("No sink for identifier: %s", identifier);
final List<FireHydrant> hydrants = Lists.newArrayList(sink);
currentHydrants.put(identifier.toString(), hydrants.size());
numPersistedRows += sink.getNumRowsInMemory();
final Stopwatch runExecStopwatch = Stopwatch.createStarted();
final Stopwatch persistStopwatch = Stopwatch.createStarted();
final ListenableFuture<Object> future = persistExecutor.submit(
new ThreadRenamingCallable<Object>(threadName)
final long startDelay = runExecStopwatch.elapsed(TimeUnit.MILLISECONDS);
metrics.incrementPersistBackPressureMillis(startDelay);
if (startDelay > WARN_DELAY) {
log.warn("Ingestion was throttled for [%,d] millis because persists were pending.", startDelay);
runExecStopwatch.stop();
resetNextFlush();
代码示例来源:origin: twitter/distributedlog
private final Stopwatch stopwatch = Stopwatch.createStarted(clockTicker);
private int nextStream;
private int numTriedStreams = 0;
代码示例来源:origin: MovingBlocks/Terasology
public ChunkMesh generateMesh(ChunkView chunkView, int meshHeight, int verticalOffset) {
PerformanceMonitor.startActivity("GenerateMesh");
ChunkMesh mesh = new ChunkMesh(bufferPool);
final Stopwatch watch = Stopwatch.createStarted();
for (int x = 0; x < ChunkConstants.SIZE_X; x++) {
for (int z = 0; z < ChunkConstants.SIZE_Z; z++) {
for (int y = verticalOffset; y < verticalOffset + meshHeight; y++) {
Block block = chunkView.getBlock(x, y, z);
if (block != null && block.getMeshGenerator() != null) {
block.getMeshGenerator().generateChunkMesh(chunkView, mesh, x, y, z);
}
}
}
}
watch.stop();
mesh.setTimeToGenerateBlockVertices((int) watch.elapsed(TimeUnit.MILLISECONDS));
watch.reset().start();
generateOptimizedBuffers(chunkView, mesh);
watch.stop();
mesh.setTimeToGenerateOptimizedBuffers((int) watch.elapsed(TimeUnit.MILLISECONDS));
statVertexArrayUpdateCount++;
PerformanceMonitor.endActivity();
return mesh;
}
代码示例来源:origin: google/guava
public void testRunWithTimeout_goodRunnableWithEnoughTime() throws Exception {
Stopwatch stopwatch = Stopwatch.createStarted();
service.runWithTimeout(GOOD_RUNNABLE, ENOUGH_MS, MILLISECONDS);
assertThat(stopwatch.elapsed(MILLISECONDS)).isIn(Range.closed(DELAY_MS, ENOUGH_MS));
}
代码示例来源:origin: google/guava
ImmutableMap<Service, Long> startupTimes() {
List<Entry<Service, Long>> loadTimes;
monitor.enter();
try {
loadTimes = Lists.newArrayListWithCapacity(startupTimers.size());
// N.B. There will only be an entry in the map if the service has started
for (Entry<Service, Stopwatch> entry : startupTimers.entrySet()) {
Service service = entry.getKey();
Stopwatch stopWatch = entry.getValue();
if (!stopWatch.isRunning() && !(service instanceof NoOpService)) {
loadTimes.add(Maps.immutableEntry(service, stopWatch.elapsed(MILLISECONDS)));
}
}
} finally {
monitor.leave();
}
Collections.sort(
loadTimes,
Ordering.natural()
.onResultOf(
new Function<Entry<Service, Long>, Long>() {
@Override
public Long apply(Entry<Service, Long> input) {
return input.getValue();
}
}));
return ImmutableMap.copyOf(loadTimes);
}
代码示例来源:origin: Alluxio/alluxio
@Override
public void run() {
Stopwatch sw = Stopwatch.createUnstarted();
Map<String, GarbageCollectorMXBean> gcBeanMapBeforeSleep = getGarbageCollectorMXBeans();
while (true) {
sw.reset().start();
try {
Thread.sleep(mGcSleepIntervalMs);
} catch (InterruptedException ie) {
LOG.warn(ie.getStackTrace());
return;
}
long extraTime = sw.elapsed(TimeUnit.MILLISECONDS) - mGcSleepIntervalMs;
mTotalExtraTimeMs += extraTime;
Map<String, GarbageCollectorMXBean> gcBeanMapAfterSleep = getGarbageCollectorMXBeans();
if (extraTime > mWarnThresholdMs) {
mInfoTimeExceeded++;
mWarnTimeExceeded++;
LOG.warn(formatLogString(extraTime, gcBeanMapBeforeSleep, gcBeanMapAfterSleep));
} else if (extraTime > mInfoThresholdMs) {
mInfoTimeExceeded++;
LOG.info(formatLogString(
extraTime, gcBeanMapBeforeSleep, gcBeanMapAfterSleep));
}
gcBeanMapBeforeSleep = gcBeanMapAfterSleep;
}
}
}
代码示例来源:origin: google/guava
public void testElapsed_multipleSegments() {
stopwatch.start();
ticker.advance(9);
stopwatch.stop();
ticker.advance(16);
stopwatch.start();
assertEquals(9, stopwatch.elapsed(NANOSECONDS));
ticker.advance(25);
assertEquals(34, stopwatch.elapsed(NANOSECONDS));
stopwatch.stop();
ticker.advance(36);
assertEquals(34, stopwatch.elapsed(NANOSECONDS));
}
代码示例来源:origin: google/guava
public void testElapsed_whileRunning() {
ticker.advance(78);
stopwatch.start();
assertEquals(0, stopwatch.elapsed(NANOSECONDS));
ticker.advance(345);
assertEquals(345, stopwatch.elapsed(NANOSECONDS));
}
代码示例来源:origin: apache/kylin
private void testEnumeratorValues(String file) throws Exception {
InputStream is = new FileInputStream(file);
ArrayList<String> str = loadStrings(is);
TrieDictionaryBuilder<String> b = newDictBuilder(str);
TrieDictionary<String> dict = b.build(0);
System.out.println("Dictionary size for file " + file + " is " + dict.getSize());
Stopwatch sw = new Stopwatch();
sw.start();
List<String> values1 = dict.enumeratorValuesByParent();
System.out.println("By iterating id visit the time cost " + sw.elapsed(TimeUnit.MILLISECONDS) + " ms");
sw.reset();
sw.start();
List<String> values2 = dict.enumeratorValues();
System.out.println("By pre-order visit the time cost " + sw.elapsed(TimeUnit.MILLISECONDS) + " ms");
sw.stop();
assertEquals(Sets.newHashSet(values1), Sets.newHashSet(values2));
}
代码示例来源:origin: google/guava
public void testPutWithNoWait() {
Stopwatch stopwatch = Stopwatch.createStarted();
BlockingQueue<String> queue = new ArrayBlockingQueue<>(999);
putUninterruptibly(queue, "");
assertTimeNotPassed(stopwatch, LONG_DELAY_MS);
assertEquals("", queue.peek());
}
代码示例来源:origin: google/guava
public void testReset_whileRunning() {
ticker.advance(1);
stopwatch.start();
assertEquals(0, stopwatch.elapsed(NANOSECONDS));
ticker.advance(2);
assertEquals(2, stopwatch.elapsed(NANOSECONDS));
stopwatch.reset();
assertFalse(stopwatch.isRunning());
ticker.advance(3);
assertEquals(0, stopwatch.elapsed(NANOSECONDS));
}
代码示例来源:origin: stackoverflow.com
Stopwatch stopwatch = Stopwatch.createStarted();
myCall();
stopwatch.stop(); // optional
System.out.println("Time elapsed for myCall() is "+ stopwatch.elapsed(MILLISECONDS));
代码示例来源:origin: apache/incubator-druid
public void profileRun()
Stopwatch watch = Stopwatch.createUnstarted();
LoadQueuePeonTester fromPeon = new LoadQueuePeonTester();
LoadQueuePeonTester toPeon = new LoadQueuePeonTester();
.build();
DruidCoordinatorBalancerTester tester = new DruidCoordinatorBalancerTester(coordinator);
watch.start();
DruidCoordinatorRuntimeParams balanceParams = tester.run(params);
System.out.println(watch.stop());
代码示例来源:origin: apache/kylin
@Test
public void createDirectChildrenCacheStressTest() {
Stopwatch sw = new Stopwatch();
sw.start();
Set<Long> cuboidSet = generateMassCuboidSet();
System.out.println("Time elapsed for creating sorted cuboid list: " + sw.elapsedMillis());
sw.reset();
sw.start();
checkDirectChildrenCacheStressTest(CuboidStatsUtil.createDirectChildrenCache(cuboidSet));
System.out.println("Time elapsed for creating direct children cache: " + sw.elapsedMillis());
sw.stop();
}
内容来源于网络,如有侵权,请联系作者删除!