下面列出了com.google.common.base.Stopwatch#createStarted ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Pre-generate enough keys to reach the lookahead size, but only if there are more than the lookaheadThreshold to
* be generated, so that the Bloom filter does not have to be regenerated that often.
* <p>
* The returned mutable list of keys must be inserted into the basic key chain.
*/
private List<DeterministicKey> maybeLookAhead(DeterministicKey parent, int issued, int lookaheadSize, int lookaheadThreshold) {
checkState(lock.isHeldByCurrentThread());
final int numChildren = hierarchy.getNumChildren(parent.getPath());
final int needed = issued + lookaheadSize + lookaheadThreshold - numChildren;
if (needed <= lookaheadThreshold)
return new ArrayList<>();
log.info("{} keys needed for {} = {} issued + {} lookahead size + {} lookahead threshold - {} num children",
needed, parent.getPathAsString(), issued, lookaheadSize, lookaheadThreshold, numChildren);
List<DeterministicKey> result = new ArrayList<>(needed);
final Stopwatch watch = Stopwatch.createStarted();
int nextChild = numChildren;
for (int i = 0; i < needed; i++) {
DeterministicKey key = HDKeyDerivation.deriveThisOrNextChildKey(parent, nextChild);
key = key.dropPrivateBytes();
hierarchy.putKey(key);
result.add(key);
nextChild = key.getChildNumber().num() + 1;
}
watch.stop();
log.info("Took {}", watch);
return result;
}
/**
* Unlocks all mappings in this map that belong to the given <see cref="MappingLockToken"/>.
*
* @param mappingLockToken
* An instance of <see cref="MappingLockToken"/>
*/
public void unlockMapping(MappingLockToken mappingLockToken) {
ExceptionUtils.disallowNullArgument(mappingLockToken, "mappingLockToken");
try (ActivityIdScope activityIdScope = new ActivityIdScope(UUID.randomUUID())) {
UUID lockOwnerId = mappingLockToken.getLockOwnerId();
log.info("UnlockAllMappingsWithLockOwnerId", "Start; LockOwnerId:{}", lockOwnerId);
Stopwatch stopwatch = Stopwatch.createStarted();
lsm.lockOrUnlockMappings(null, lockOwnerId, LockOwnerIdOpType.UnlockAllMappingsForId);
stopwatch.stop();
log.info("UnlockAllMappingsWithLockOwnerId", "Complete; Duration:{}", stopwatch.elapsed(TimeUnit.MILLISECONDS));
}
}
@Override
public void run() {
final DLSN dlsnToTruncate = prevDLSN;
if (null == dlsnToTruncate) {
return;
}
final Stopwatch stopwatch = Stopwatch.createStarted();
dlc.truncate(streamName, dlsnToTruncate).addEventListener(
new FutureEventListener<Boolean>() {
@Override
public void onSuccess(Boolean value) {
truncationStat.registerSuccessfulEvent(
stopwatch.stop().elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS);
}
@Override
public void onFailure(Throwable cause) {
truncationStat.registerFailedEvent(
stopwatch.stop().elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS);
LOG.error("Failed to truncate stream {} to {} : ",
new Object[]{streamName, dlsnToTruncate, cause});
}
});
}
@Test
public void testInvokeEffectorWithTimeoutWaits() throws Exception {
String path = "/applications/"+app.getId()+"/entities/"+entity.getId()+"/effectors/"+"sleepEffector";
Stopwatch stopwatch = Stopwatch.createStarted();
Response response = client().path(path)
.query("timeout", "1m")
.accept(MediaType.APPLICATION_JSON)
.header("Content-Type", MediaType.APPLICATION_JSON)
.post("{\"duration\": \"50ms\"}");
Duration runDuration = Duration.of(stopwatch);
assertEquals(response.getStatus(), 202);
assertTrue(entity.getCallHistory().contains("sleepEffector"));
assertTrue(runDuration.isLongerThan(Duration.millis(40)), "runDuration="+runDuration);
}
public static void main(String[] args) throws IOException {
OptionParser.setArgsOptions(ParallelPC.class, args);
BayesianNetworkGenerator.loadOptions();
BayesianNetworkGenerator.setNumberOfGaussianVars(0);
BayesianNetworkGenerator.setNumberOfMultinomialVars(100, 10);
BayesianNetworkGenerator.setSeed(0);
BayesianNetwork bn = BayesianNetworkGenerator.generateNaiveBayes(2);
int sampleSize = 5000;
BayesianNetworkSampler sampler = new BayesianNetworkSampler(bn);
sampler.loadOptions();
DataStream<DataInstance> data = sampler.sampleToDataStream(sampleSize);
for (int i = 1; i <= 4; i++) {
int samplesOnMemory = 1000;
int numCores = i;
System.out.println("Learning PC: " + samplesOnMemory + " samples on memory, " + numCores + "core/s ...");
ParallelPC parallelPC = new ParallelPC();
parallelPC.setOptions(args);
//tan.loadOptionsFromFile("configurationFiles/conf.txt");
parallelPC.setNumCores(numCores);
parallelPC.setNumSamplesOnMemory(samplesOnMemory);
Stopwatch watch = Stopwatch.createStarted();
BayesianNetwork model = parallelPC.learn(data);
System.out.println(watch.stop());
}
}
@Override
public void initOsgi() {
synchronized (reloadLock) {
final Stopwatch startupTimer = Stopwatch.createStarted();
BrooklynShutdownHooks.resetShutdownFlag();
LOG.debug("OsgiLauncher init, catalog "+defaultCatalogLocation);
catalogInitialization(new CatalogInitialization(String.format("file:%s", defaultCatalogLocation)));
startPartOne();
startupTimer.stop();
LOG.info("Brooklyn initialisation (part one) complete after {}", startupTimer.toString());
}
}
private static void updateSchemaWithRetry(com.datastax.driver.core.Session wrappedSession,
String query) throws InterruptedException {
Stopwatch stopwatch = Stopwatch.createStarted();
while (stopwatch.elapsed(SECONDS) < 60) {
try {
wrappedSession.execute(query);
return;
} catch (NoHostAvailableException e) {
logger.debug(e.getMessage(), e);
}
SECONDS.sleep(1);
}
// try one last time and let exception bubble up
wrappedSession.execute(query);
}
public ReadAheadCache(String streamName,
StatsLogger statsLogger,
AlertStatsLogger alertStatsLogger,
AsyncNotification notification,
int maxCachedRecords,
boolean deserializeRecordSet,
boolean traceDeliveryLatencyEnabled,
long deliveryLatencyWarnThresholdMillis,
Ticker ticker) {
this.streamName = streamName;
this.maxCachedRecords = maxCachedRecords;
this.notification = notification;
this.deserializeRecordSet = deserializeRecordSet;
// create the readahead queue
readAheadRecords = new LinkedBlockingQueue<LogRecordWithDLSN>();
// start the idle reader detection
lastEntryProcessTime = Stopwatch.createStarted(ticker);
// Flags to control delivery latency tracing
this.traceDeliveryLatencyEnabled = traceDeliveryLatencyEnabled;
this.deliveryLatencyWarnThresholdMillis = deliveryLatencyWarnThresholdMillis;
// Stats
StatsLogger readAheadStatsLogger = statsLogger.scope("readahead");
this.statsLogger = readAheadStatsLogger;
this.alertStatsLogger = alertStatsLogger;
this.readAheadDeliveryLatencyStat =
readAheadStatsLogger.getOpStatsLogger("delivery_latency");
this.negativeReadAheadDeliveryLatencyStat =
readAheadStatsLogger.getOpStatsLogger("negative_delivery_latency");
}
@Test
public void retryer_should_wait_after_failure_before_trying_again() throws Exception {
Retryer timeRetryer = new Retryer(1, Duration.millis(100));
Stopwatch stopwatch = Stopwatch.createStarted();
when(operation.call()).thenThrow(new DockerExecutionException()).thenAnswer(i -> {
assertThat(stopwatch.elapsed(TimeUnit.MILLISECONDS), greaterThan(100L));
return "success";
});
String result = timeRetryer.runWithRetries(operation);
assertThat(result, is("success"));
}
@Override
public Network importData(ReadOnlyDataSource dataSource, NetworkFactory networkFactory, Properties parameters) {
try {
String ext = findExtension(dataSource, true);
try (BufferedReader reader = new BufferedReader(new InputStreamReader(dataSource.newInputStream(null, ext)))) {
Stopwatch stopwatch = Stopwatch.createStarted();
UcteNetworkExt ucteNetwork = new UcteNetworkExt(new UcteReader().read(reader), LINE_MIN_Z);
String fileName = dataSource.getBaseName();
EntsoeFileName ucteFileName = EntsoeFileName.parse(fileName);
Network network = networkFactory.createNetwork(fileName, "UCTE");
network.setCaseDate(ucteFileName.getDate());
network.setForecastDistance(ucteFileName.getForecastDistance());
createBuses(ucteNetwork, network);
createLines(ucteNetwork, network);
createTransformers(ucteNetwork, network, ucteFileName);
mergeXnodeDanglingLines(ucteNetwork, network);
stopwatch.stop();
LOGGER.debug("UCTE import done in {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
return network;
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/**
* Read the tuples
* @param tupleStore
* @return
* @throws IOException
*/
protected long readTuplesRandom(final SSTableTupleStore tupleStore) throws Exception {
System.out.println("# Reading Tuples random");
final Stopwatch stopwatch = Stopwatch.createStarted();
final Random random = new Random();
for(int i = 0; i < TUPLES; i++) {
tupleStore.readTuple(Integer.toString(random.nextInt(TUPLES)));
}
return stopwatch.elapsed(TimeUnit.MILLISECONDS);
}
@Override
public void run() {
if (counter.isOutdated()) {
log.info("Thread for timestamp " + toString() + " is outdated, not running");
return;
}
Stopwatch stopwatch = Stopwatch.createStarted();
try (Socket socket = createSocket()) {
try (BufferedOutputStream outputStream = new BufferedOutputStream(socket.getOutputStream())) {
for (int i = 1; i <= count; i++) {
if (counter.isOutdated()) {
log.info(
"Stopping metric send for timestamp " + timestamp + " cause outdated. " +
"Sent " + i + "metrics, " + (count - i) + " left."
);
return;
}
double value = ThreadLocalRandom.current().nextDouble(1000);
String line = prefix + "metric" + i + " " + value + " " + timestamp + "\n";
outputStream.write(line.getBytes());
}
}
stopwatch.stop();
counter.onSuccess(count, stopwatch.elapsed(TimeUnit.NANOSECONDS));
} catch (Exception e) {
log.warn("Failed to send " + count + " metrics " + e.getMessage());
counter.onFail(count);
}
}
/**
* Handshake with all proxies.
*
* <p>NOTE: this is a synchronous call.
*/
public void handshake() {
Set<SocketAddress> hostsSnapshot = hostProvider.getHosts();
logger.info("Handshaking with {} hosts.", hostsSnapshot.size());
final CountDownLatch latch = new CountDownLatch(hostsSnapshot.size());
final Stopwatch stopwatch = Stopwatch.createStarted();
for (SocketAddress host: hostsSnapshot) {
final SocketAddress address = host;
final ProxyClient client = getClient(address);
handshake(address, client, new FutureEventListener<ServerInfo>() {
@Override
public void onSuccess(ServerInfo serverInfo) {
notifyHandshakeSuccess(address, client, serverInfo, true, stopwatch);
latch.countDown();
}
@Override
public void onFailure(Throwable cause) {
notifyHandshakeFailure(address, client, cause, stopwatch);
latch.countDown();
}
}, true, true);
}
try {
latch.await(1, TimeUnit.MINUTES);
} catch (InterruptedException e) {
logger.warn("Interrupted on handshaking with servers : ", e);
}
}
public long execute(final Phase phase) throws Exception {
phase.initialize();
final Stopwatch stopwatch = Stopwatch.createStarted();
phase.run();
stopwatch.stop();
phase.cleanup();
return stopwatch.elapsed(TimeUnit.NANOSECONDS);
}
/**
* Updates the state with the given service transition.
*
* <p>This method performs the main logic of ServiceManager in the following steps.
* <ol>
* <li>Update the {@link #servicesByState()}
* <li>Update the {@link #startupTimers}
* <li>Based on the new state queue listeners to run
* <li>Run the listeners (outside of the lock)
* </ol>
*/
void transitionService(
final Service service, State from, State to) {
checkNotNull(service);
checkArgument(from != to);
monitor.enter();
try {
transitioned = true;
if (!ready) {
return;
}
// Update state.
checkState(
servicesByState.remove(from, service),
"Service %s not at the expected location in the state map %s",
service,
from);
checkState(
servicesByState.put(to, service),
"Service %s in the state map unexpectedly at %s",
service,
to);
// Update the timer
Stopwatch stopwatch = startupTimers.get(service);
if (stopwatch == null) {
// This means the service was started by some means other than ServiceManager.startAsync
stopwatch = Stopwatch.createStarted();
startupTimers.put(service, stopwatch);
}
if (to.compareTo(RUNNING) >= 0 && stopwatch.isRunning()) {
// N.B. if we miss the STARTING event then we may never record a startup time.
stopwatch.stop();
if (!(service instanceof NoOpService)) {
logger.log(Level.FINE, "Started {0} in {1}.", new Object[] {service, stopwatch});
}
}
// Queue our listeners
// Did a service fail?
if (to == FAILED) {
fireFailedListeners(service);
}
if (states.count(RUNNING) == numberOfServices) {
// This means that the manager is currently healthy. N.B. If other threads call isHealthy
// they are not guaranteed to get 'true', because any service could fail right now.
fireHealthyListeners();
} else if (states.count(TERMINATED) + states.count(FAILED) == numberOfServices) {
fireStoppedListeners();
}
} finally {
monitor.leave();
// Run our executors outside of the lock
executeListeners();
}
}
public static <T, U> void saveWithTimeLog(BiConsumer<T, U> bi, T t, U u) {
Stopwatch st = Stopwatch.createStarted();
bi.accept(t, u);
Stopwatch st1 = st.stop();
log.debug("{} save succeed, use time {}ms", u.getClass().getName(), st1.elapsed(TimeUnit.MILLISECONDS));
}
void close(boolean jvmTermination) throws InterruptedException {
if (confDirWatchExecutor != null && !jvmTermination) {
// shutdownNow() is needed here to send interrupt to conf dir watching thread
confDirWatchExecutor.shutdownNow();
if (!confDirWatchExecutor.awaitTermination(10, SECONDS)) {
throw new IllegalStateException(
"Timed out waiting for conf dir watching thread to terminate");
}
}
// immediately start sending "shutting-down" responses for new downstream requests
// and wait for existing downstream requests to complete before proceeding
downstreamService.stopSendingDownstreamRequests();
// "shutting-down" responses will continue to be sent for new downstream requests until
// ClusterManager is closed at the very end of CentralModule.shutdown(), which will give
// time for agents to reconnect to a new central cluster node, and for the UI to retry
// for a few seconds if it receives a "shutting-down" response
if (httpsServer != null) {
// stop accepting new requests
httpsServer.shutdown();
}
if (httpServer != null) {
// stop accepting new requests
httpServer.shutdown();
}
Stopwatch stopwatch = Stopwatch.createStarted();
if (httpsServer != null) {
// wait for existing requests to complete
while (stopwatch.elapsed(SECONDS) < 5) {
if (httpsServer.isTerminated()) {
break;
}
Thread.sleep(10);
}
}
if (httpServer != null) {
// wait for existing requests to complete
while (stopwatch.elapsed(SECONDS) < 5) {
if (httpServer.isTerminated()) {
break;
}
Thread.sleep(10);
}
}
if (httpsServer != null && !httpsServer.isTerminated()) {
httpsServer.shutdownNow();
}
if (httpServer != null && !httpServer.isTerminated()) {
httpServer.shutdownNow();
}
stopwatch = Stopwatch.createStarted();
if (httpsServer != null && !httpsServer.isTerminated()
&& !httpsServer.awaitTermination(5, SECONDS)) {
throw new IllegalStateException("Timed out waiting for grpc server to terminate");
}
long remainingMillis = Math.max(0, 5000 - stopwatch.elapsed(MILLISECONDS));
if (httpServer != null && !httpServer.isTerminated()
&& !httpServer.awaitTermination(remainingMillis, MILLISECONDS)) {
throw new IllegalStateException("Timed out waiting for grpc server to terminate");
}
}
static void runTask(Task task, PrintWriter pw) throws ExecutionException, InterruptedException {
Stopwatch stopwatch = Stopwatch.createStarted();
switch (task) {
case createDatabase:
createDatabase(pw);
break;
case writeExampleData:
writeExampleData(pw);
break;
case query:
query(pw);
break;
case read:
read(pw);
break;
case addMarketingBudget:
addMarketingBudgetColumnToAlbums(pw);
break;
case updateMarketingBudget:
updateMarketingBudgetData();
break;
case queryMarketingBudget:
queryMarketingBudget(pw);
break;
case addIndex:
addIndex();
break;
case readUsingIndex:
readUsingIndex(pw);
break;
case queryUsingIndex:
queryUsingIndex(pw);
break;
case addStoringIndex:
addStoringIndex();
break;
case readStoringIndex:
readStoringIndex(pw);
break;
case readOnlyTransaction:
readOnlyTransaction(pw);
break;
case writeTransaction:
writeWithTransaction();
break;
default:
break;
}
stopwatch.stop();
pw.println(task + " in milliseconds : " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
pw.println("====================================================================");
}
@BeforeClass
public static void setUpClass() throws Exception {
HELPER=new ServerFrontendTestHelper(LOGGER);
WATCH=Stopwatch.createStarted();
}
@Override
public void addComplete(final int rc, LedgerHandle handle,
final long entryId, final Object ctx) {
final AtomicReference<Integer> effectiveRC = new AtomicReference<Integer>(rc);
try {
if (FailpointUtils.checkFailPoint(FailpointUtils.FailPointName.FP_TransmitComplete)) {
effectiveRC.set(BKException.Code.UnexpectedConditionException);
}
} catch (Exception exc) {
effectiveRC.set(BKException.Code.UnexpectedConditionException);
}
// Sanity check to make sure we're receiving these callbacks in order.
if (entryId > -1 && lastEntryId >= entryId) {
LOG.error("Log segment {} saw out of order entry {} lastEntryId {}",
new Object[] {fullyQualifiedLogSegment, entryId, lastEntryId});
}
lastEntryId = entryId;
assert (ctx instanceof BKTransmitPacket);
final BKTransmitPacket transmitPacket = (BKTransmitPacket) ctx;
// Time from transmit until receipt of addComplete callback
addCompleteTime.registerSuccessfulEvent(TimeUnit.MICROSECONDS.convert(
System.nanoTime() - transmitPacket.getTransmitTime(), TimeUnit.NANOSECONDS));
if (BKException.Code.OK == rc) {
EntryBuffer recordSet = transmitPacket.getRecordSet();
if (recordSet.hasUserRecords()) {
synchronized (this) {
lastTxIdAcknowledged = Math.max(lastTxIdAcknowledged, recordSet.getMaxTxId());
}
}
}
if (null != addCompleteFuturePool) {
final Stopwatch queuedTime = Stopwatch.createStarted();
addCompleteFuturePool.apply(new Function0<Void>() {
public Void apply() {
final Stopwatch deferredTime = Stopwatch.createStarted();
addCompleteQueuedTime.registerSuccessfulEvent(queuedTime.elapsed(TimeUnit.MICROSECONDS));
addCompleteDeferredProcessing(transmitPacket, entryId, effectiveRC.get());
addCompleteDeferredTime.registerSuccessfulEvent(deferredTime.elapsed(TimeUnit.MICROSECONDS));
return null;
}
@Override
public String toString() {
return String.format("AddComplete(Stream=%s, entryId=%d, rc=%d)",
fullyQualifiedLogSegment, entryId, rc);
}
}).addEventListener(new FutureEventListener<Void>() {
@Override
public void onSuccess(Void done) {
}
@Override
public void onFailure(Throwable cause) {
LOG.error("addComplete processing failed for {} entry {} lastTxId {} rc {} with error",
new Object[] {fullyQualifiedLogSegment, entryId, transmitPacket.getRecordSet().getMaxTxId(), rc, cause});
}
});
// Race condition if we notify before the addComplete is enqueued.
transmitPacket.notifyTransmitComplete(effectiveRC.get());
outstandingTransmits.getAndDecrement();
} else {
// Notify transmit complete must be called before deferred processing in the
// sync case since otherwise callbacks in deferred processing may deadlock.
transmitPacket.notifyTransmitComplete(effectiveRC.get());
outstandingTransmits.getAndDecrement();
addCompleteDeferredProcessing(transmitPacket, entryId, effectiveRC.get());
}
}