com.google.common.base.Stopwatch#createStarted ( )源码实例Demo

下面列出了com.google.common.base.Stopwatch#createStarted ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: bcm-android   文件: DeterministicKeyChain.java
/**
 * 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;
}
 
源代码2 项目: elastic-db-tools-for-java   文件: ListShardMap.java
/**
 * 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));
    }
}
 
源代码3 项目: distributedlog   文件: ReaderWorker.java
@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});
                }
            });
}
 
源代码4 项目: brooklyn-server   文件: EffectorResourceTest.java
@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);
}
 
源代码5 项目: toolbox   文件: ParallelPC.java
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());
        }
    }
 
源代码6 项目: brooklyn-server   文件: OsgiLauncherImpl.java
@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());
    }
}
 
源代码7 项目: glowroot   文件: Session.java
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);
}
 
源代码8 项目: distributedlog   文件: ReadAheadCache.java
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");
}
 
源代码9 项目: docker-compose-rule   文件: RetryerShould.java
@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"));
}
 
源代码10 项目: powsybl-core   文件: UcteImporter.java
@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);
    }
}
 
源代码11 项目: bboxdb   文件: TestSSTableBloomFilter.java
/**
 * 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);
}
 
源代码12 项目: graphouse   文件: InsertTest.java
@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);
    }
}
 
源代码13 项目: distributedlog   文件: ProxyClientManager.java
/**
 * 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);
    }
}
 
源代码14 项目: trainbenchmark   文件: PhaseExecutor.java
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);
}
 
源代码15 项目: codebuff   文件: ServiceManager.java
/**
 * 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();
  }
}
 
源代码16 项目: WeBASE-Collect-Bee   文件: BaseDAO.java
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));
}
 
源代码17 项目: glowroot   文件: GrpcServer.java
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");
    }
}
 
源代码18 项目: java-docs-samples   文件: SpannerTasks.java
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("====================================================================");
}
 
源代码19 项目: ldp4j   文件: ServerFrontendITest.java
@BeforeClass
public static void setUpClass() throws Exception {
	HELPER=new ServerFrontendTestHelper(LOGGER);
	WATCH=Stopwatch.createStarted();
}
 
源代码20 项目: distributedlog   文件: BKLogSegmentWriter.java
@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());
    }
}