本文整理汇总了Java中com.google.common.base.Stopwatch.elapsed方法的典型用法代码示例。如果您正苦于以下问题:Java Stopwatch.elapsed方法的具体用法?Java Stopwatch.elapsed怎么用?Java Stopwatch.elapsed使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.google.common.base.Stopwatch
的用法示例。
在下文中一共展示了Stopwatch.elapsed方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: handleSlowMethod
import com.google.common.base.Stopwatch; //导入方法依赖的package包/类
@RequestMapping("/slowmethod/{name}")
@ResponseBody
public String handleSlowMethod(HttpServletRequest servletRequest, @PathVariable("name") String name) {
HttpSession session = servletRequest.getSession(false);
if (session == null) {
log.debug("created new session to save name '" + name + "'");
// no session was created yet, create a new one and set some session
// data specific to this user/request
session = servletRequest.getSession(true);
session.setAttribute("complex", new SessionObject(name));
}
Stopwatch stopwatch = Stopwatch.createStarted();
// simulate a slow method by calculating some stuff that should take
// some hundreds milliseconds. We do NOT use Thread.sleep because we
// want to measure cpu perfomance differences on heavy load (takes ~100ms on my machine).
long count = 0;
for (long i = 0; i < 250000000l; i++) {
count++;
}
return "hello, your session is: " + session + ", count is: " + count + " elapsed time is: "+stopwatch.elapsed(TimeUnit.MILLISECONDS)+", your name is: "
+ ((SessionObject) session.getAttribute("complex")).getName() + "\n" + getHostInfo();
}
示例2: waitForMembersUp
import com.google.common.base.Stopwatch; //导入方法依赖的package包/类
static void waitForMembersUp(final ActorSystem node, final UniqueAddress... addresses) {
Set<UniqueAddress> otherMembersSet = Sets.newHashSet(addresses);
Stopwatch sw = Stopwatch.createStarted();
while (sw.elapsed(TimeUnit.SECONDS) <= 10) {
CurrentClusterState state = Cluster.get(node).state();
for (Member m : state.getMembers()) {
if (m.status() == MemberStatus.up() && otherMembersSet.remove(m.uniqueAddress())
&& otherMembersSet.isEmpty()) {
return;
}
}
Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
}
fail("Member(s) " + otherMembersSet + " are not Up");
}
示例3: putDS
import com.google.common.base.Stopwatch; //导入方法依赖的package包/类
@VisibleForTesting
public VirtualDatasetUI putDS(String spaceName, List<FolderName> folderPath, String name, From from)
throws NamespaceException, DatasetNotFoundException {
Stopwatch sw = Stopwatch.createStarted();
DatasetPath datasetPath = new DatasetPath(
spaceName.startsWith(HOME_PREFIX) ? new HomeName(spaceName) : new SpaceName(spaceName),
folderPath,
new DatasetName(name));
VirtualDatasetUI ds = newDataset(datasetPath, newVersion(), from, datasetPath.toParentPathList());
datasetService.put(ds);
long t = sw.elapsed(MILLISECONDS);
if ( t > 100) {
logger.warn(String.format("creating dataset %s took %dms", datasetPath, t));
}
return ds;
}
示例4: sumbitVote
import com.google.common.base.Stopwatch; //导入方法依赖的package包/类
@Override
public List<String> sumbitVote(String identificationCredentials, List<Integer> selections) throws VoteCastingException {
Preconditions.checkState(publicParameters != null,
"The public parameters need to have been retrieved first");
Preconditions.checkState(electionSet != null,
"The electionSet needs to have been retrieved first");
Stopwatch stopwatch = Stopwatch.createStarted();
List<EncryptionPublicKey> publicKeyParts = bulletinBoardService.getPublicKeyParts();
EncryptionPublicKey systemPublicKey = keyEstablishmentAlgorithms.getPublicKey(publicKeyParts);
BallotQueryAndRand ballotQueryAndRand = computeBallot(identificationCredentials, selections, systemPublicKey);
randomizations = ballotQueryAndRand.getBold_r();
stopwatch.stop();
stats.voteEncodingTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);
List<ObliviousTransferResponse> obliviousTransferResponses = sentBallotAndQuery(ballotQueryAndRand.getAlpha());
stopwatch.reset().start();
pointMatrix = computePointMatrix(selections, obliviousTransferResponses);
List<String> returnCodes = voteCastingClientAlgorithms.getReturnCodes(selections, pointMatrix);
stopwatch.stop();
stats.verificationCodesComputationTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);
return returnCodes;
}
示例5: verifyNodeRemoved
import com.google.common.base.Stopwatch; //导入方法依赖的package包/类
protected void verifyNodeRemoved(YangInstanceIdentifier path,
Function<YangInstanceIdentifier,NormalizedNode<?,?>> reader) {
AssertionError lastError = null;
Stopwatch sw = Stopwatch.createStarted();
while (sw.elapsed(TimeUnit.MILLISECONDS) <= 5000) {
try {
NormalizedNode<?, ?> node = reader.apply(path);
Assert.assertNull("Node was not removed at path: " + path, node);
return;
} catch (AssertionError e) {
lastError = e;
Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
}
}
throw lastError;
}
示例6: close
import com.google.common.base.Stopwatch; //导入方法依赖的package包/类
@Override
public void close() throws Exception {
try {
Stopwatch watch = Stopwatch.createStarted();
// this takes 1s to complete
// known issue: https://github.com/netty/netty/issues/2545
eventLoop.shutdownGracefully(0, 0, TimeUnit.SECONDS);
eventLoop.terminationFuture().sync();
long elapsed = watch.elapsed(MILLISECONDS);
if (elapsed > 1200) {
logger.info("closed eventLoopGroups in " + elapsed + " ms");
}
} catch (final InterruptedException e) {
logger.warn("Failure while shutting down bootstrap context event loops.", e);
// Preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the
// interruption and respond to it if it wants to.
Thread.currentThread().interrupt();
}
}
示例7: stressEndpoint
import com.google.common.base.Stopwatch; //导入方法依赖的package包/类
private Duration stressEndpoint(long iterations, int threads, String path, String expectedString, boolean checkForSessionDataCookie) throws InterruptedException {
final Stopwatch stopWatch = Stopwatch.createStarted();
final ExecutorService threadPool = Executors.newFixedThreadPool(threads);
final Runnable command = new Runnable() {
@Override
public void run() {
for (int i = 0; i < iterations; i++) {
final Response response = given().get(HOST + path);
response.then().assertThat().body(containsString(expectedString));
final Cookies cookies = response.getDetailedCookies();
if (checkForSessionDataCookie) {
assertTrue("no sessiondata cookie exists", cookies.hasCookieWithName(SessionToCookieFilter.SESSIONDATACOOKIENAME));
}
}
}
};
for (int i = 0; i < threads; i++) {
threadPool.execute(command);
}
threadPool.shutdown();
final boolean finished = threadPool.awaitTermination(10, TimeUnit.SECONDS);
stopWatch.stop();
if (!finished) {
LOG.debug("wuaaaah, tasks took longer than 10 seconds. aborted execution since this test should not run that long");
}
return stopWatch.elapsed();
}
示例8: assertAtLeastTimePassed
import com.google.common.base.Stopwatch; //导入方法依赖的package包/类
private static void assertAtLeastTimePassed(
Stopwatch stopwatch, long expectedMillis) {
long elapsedMillis = stopwatch.elapsed(MILLISECONDS);
/*
* The "+ 5" below is to permit, say, sleep(10) to sleep only 9 milliseconds. We see such
* behavior sometimes when running these tests publicly as part of Guava. "+ 5" is probably
* more generous than it needs to be.
*/
assertTrue("Expected elapsed millis to be >= " + expectedMillis
+ " but was " + elapsedMillis, elapsedMillis + 5 >= expectedMillis);
}
示例9: verifyRaftState
import com.google.common.base.Stopwatch; //导入方法依赖的package包/类
private static void verifyRaftState(RaftState expState, RaftActor... raftActors) {
Stopwatch sw = Stopwatch.createStarted();
while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
for (RaftActor raftActor : raftActors) {
if (raftActor.getRaftState() == expState) {
return;
}
}
}
fail("None of the RaftActors have state " + expState);
}
示例10: writeToStream
import com.google.common.base.Stopwatch; //导入方法依赖的package包/类
public void writeToStream(FSDataOutputStream stream) throws IOException {
Stopwatch watch = new Stopwatch();
watch.start();
available = false;
check = ThreadLocalRandom.current().nextLong();
start = stream.getPos();
logger.debug("Writing check value {} at position {}", check, start);
stream.writeLong(check);
batch.getHeader().writeDelimitedTo(stream);
ByteBuf buf = batch.getBody();
if (buf != null) {
bodyLength = buf.capacity();
} else {
bodyLength = 0;
}
if (bodyLength > 0) {
buf.getBytes(0, stream, bodyLength);
}
stream.hsync();
FileStatus status = fs.getFileStatus(path);
long len = status.getLen();
logger.debug("After spooling batch, stream at position {}. File length {}", stream.getPos(), len);
batch.sendOk();
latch.countDown();
long t = watch.elapsed(TimeUnit.MICROSECONDS);
logger.debug("Took {} us to spool {} to disk. Rate {} mb/s", t, bodyLength, bodyLength / t);
if (buf != null) {
buf.release();
}
}
示例11: readFile
import com.google.common.base.Stopwatch; //导入方法依赖的package包/类
private Map<Long, List<AlternativeName>> readFile(String filename, String alternativeParamName, boolean hasSideName) {
Map<Long, List<AlternativeName>> alternates = newHashMap();
File file = new File(folder.getFile(filename));
if (file.exists()) {
log.info("Reading {}", file);
try (DbfReader reader = new DbfReader(file)) {
DbfRow row;
Stopwatch stopwatch = Stopwatch.createStarted();
int counter = 0;
while ((row = reader.nextRow()) != null) {
AlternativeName altName = AlternativeName.fromDbf(row, alternativeParamName, hasSideName);
List<AlternativeName> altNames = alternates.containsKey(altName.getId()) ? alternates.get(altName.getId()) : newArrayList();
altNames.add(altName);
alternates.put(altName.getId(), altNames);
counter++;
}
long time = stopwatch.elapsed(MILLISECONDS);
stopwatch.stop();
log.info("Added {} object(s){}", counter, counter > 0 ? " in " + time + " ms at rate " + String.format("%.2f", counter * 1.0 / time) + " obj/ms" : "");
}
} else {
log.info("File not found : {}", file.getAbsolutePath());
}
return alternates;
}
示例12: testTempFileDeletedOnGC
import com.google.common.base.Stopwatch; //导入方法依赖的package包/类
@Test
public void testTempFileDeletedOnGC() throws IOException {
LOG.info("testTempFileDeletedOnGC starting");
FileBackedOutputStream fbos = null;
try {
fbos = new FileBackedOutputStream(1, TEMP_DIR);
fbos.write(new byte[] {0, 1});
assertNotNull("Expected temp file created", findTempFileName(TEMP_DIR));
} finally {
if (fbos != null) {
fbos.close();
}
fbos = null;
}
Stopwatch sw = Stopwatch.createStarted();
while (sw.elapsed(TimeUnit.SECONDS) <= 20) {
System.gc();
if (findTempFileName(TEMP_DIR) == null) {
return;
}
Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
}
fail("Temp file was not deleted");
}
示例13: updateDS
import com.google.common.base.Stopwatch; //导入方法依赖的package包/类
@VisibleForTesting
public VirtualDatasetUI updateDS(DatasetPath datasetPath, Long savedVersion, From from)
throws NamespaceException, DatasetNotFoundException {
Stopwatch sw = Stopwatch.createStarted();
VirtualDatasetUI ds = newDataset(datasetPath, newVersion(), from, datasetPath.toParentPathList());
ds.setSavedVersion(savedVersion);
datasetService.putVersion(ds);
long t = sw.elapsed(MILLISECONDS);
if ( t > 100) {
logger.warn(String.format("creating dataset %s took %dms", datasetPath, t));
}
return ds;
}
示例14: setup
import com.google.common.base.Stopwatch; //导入方法依赖的package包/类
@Before
@SuppressWarnings("IllegalCatch")
public void setup() throws Exception {
String moduleName = getModuleName();
String instanceName = getInstanceName();
if (moduleName == null || instanceName == null) {
return;
}
LOG.info("Module: {} Instance: {} attempting to configure.", moduleName, instanceName);
Stopwatch stopWatch = Stopwatch.createStarted();
ObjectName objectName = null;
for (int i = 0; i < MODULE_TIMEOUT_MILLIS; i++) {
try {
ConfigRegistry configRegistryClient = new ConfigRegistryJMXClient(
ManagementFactory.getPlatformMBeanServer());
objectName = configRegistryClient.lookupConfigBean(moduleName, instanceName);
LOG.info("Module: {} Instance: {} ObjectName: {}.", moduleName, instanceName, objectName);
break;
} catch (final Exception e) {
if (i < MODULE_TIMEOUT_MILLIS) {
Thread.sleep(1);
continue;
} else {
throw e;
}
}
}
if (objectName != null) {
LOG.info("Module: {} Instance: {} configured after {} ms", moduleName, instanceName,
stopWatch.elapsed(TimeUnit.MILLISECONDS));
} else {
throw new RuntimeException("NOT FOUND Module: " + moduleName + " Instance: " + instanceName
+ " configured after " + stopWatch.elapsed(TimeUnit.MILLISECONDS) + " ms");
}
}
示例15: writeToStream
import com.google.common.base.Stopwatch; //导入方法依赖的package包/类
public void writeToStream(FSDataOutputStream stream) throws IOException {
Stopwatch watch = Stopwatch.createStarted();
ByteBuf buf = null;
try {
check = ThreadLocalRandom.current().nextLong();
start = stream.getPos();
logger.debug("Writing check value {} at position {}", check, start);
stream.writeLong(check);
batch.getHeader().writeDelimitedTo(stream);
buf = batch.getBody();
if (buf != null) {
bodyLength = buf.capacity();
} else {
bodyLength = 0;
}
if (bodyLength > 0) {
buf.getBytes(0, stream, bodyLength);
}
stream.hsync();
FileStatus status = spillFile.getFileStatus();
long len = status.getLen();
logger.debug("After spooling batch, stream at position {}. File length {}", stream.getPos(), len);
long t = watch.elapsed(TimeUnit.MICROSECONDS);
logger.debug("Took {} us to spool {} to disk. Rate {} mb/s", t, bodyLength, bodyLength / t);
} finally {
// even if the try block throws an exception we still want to send an ACK and release the lock
// the caller will add the exception to deferred attribute and it will be thrown when the poll() method is called
try {
batch.sendOk(); // this can also throw an exception
} finally {
state = BatchState.SPILLED;
batch = null;
if (buf != null) {
buf.release();
}
}
}
}