类com.google.common.base.Stopwatch源码实例Demo

下面列出了怎么用com.google.common.base.Stopwatch的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: green_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.
 *
 * 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 项目: meghanada-server   文件: ASMReflectorTest.java
@Test
public void testReflectInterface1() throws Exception {
  ASMReflector asmReflector = ASMReflector.getInstance();
  Stopwatch stopwatch = Stopwatch.createUnstarted();
  {
    String fqcn = "com.google.common.eventbus.SubscriberExceptionHandler";
    File jar = getJar("guava:guava:");
    Map<String, ClassIndex> index = asmReflector.getClassIndexes(jar);
    final InheritanceInfo info = asmReflector.getReflectInfo(index, fqcn);

    stopwatch.start();
    List<MemberDescriptor> memberDescriptors = asmReflector.reflectAll(info);
    System.out.println(stopwatch.stop());
    memberDescriptors.forEach(
        m -> {
          System.out.println(m.getDeclaration());
          System.out.println("Return: " + m.getRawReturnType());
        });
    assertEquals(1, memberDescriptors.size());
    stopwatch.reset();
  }
}
 
源代码3 项目: glowroot   文件: TraceCollector.java
Trace getPartialTrace(int timeout, TimeUnit unit) throws InterruptedException {
    Stopwatch stopwatch = Stopwatch.createStarted();
    while (stopwatch.elapsed(unit) < timeout) {
        for (Trace trace : traces) {
            if (trace.getHeader().getPartial()) {
                return trace;
            }
        }
        MILLISECONDS.sleep(10);
    }
    if (traces.isEmpty()) {
        throw new IllegalStateException("No trace was collected");
    } else {
        throw new IllegalStateException("Trace was collected but is not partial");
    }
}
 
源代码4 项目: GreenBits   文件: MnemonicCode.java
/**
 * Convert mnemonic word list to seed.
 */
public static byte[] toSeed(List<String> words, String passphrase) {

    // To create binary seed from mnemonic, we use PBKDF2 function
    // with mnemonic sentence (in UTF-8) used as a password and
    // string "mnemonic" + passphrase (again in UTF-8) used as a
    // salt. Iteration count is set to 4096 and HMAC-SHA512 is
    // used as a pseudo-random function. Desired length of the
    // derived key is 512 bits (= 64 bytes).
    //
    String pass = Utils.join(words);
    String salt = "mnemonic" + passphrase;

    final Stopwatch watch = Stopwatch.createStarted();
    byte[] seed = PBKDF2SHA512.derive(pass, salt, PBKDF2_ROUNDS, 64);
    watch.stop();
    log.info("PBKDF2 took {}", watch);
    return seed;
}
 
源代码5 项目: grpc-nebula-java   文件: InternalSubchannel.java
InternalSubchannel(List<EquivalentAddressGroup> addressGroups, String authority, String userAgent,
    BackoffPolicy.Provider backoffPolicyProvider,
    ClientTransportFactory transportFactory, ScheduledExecutorService scheduledExecutor,
    Supplier<Stopwatch> stopwatchSupplier, SynchronizationContext syncContext, Callback callback,
    InternalChannelz channelz, CallTracer callsTracer, ChannelTracer channelTracer,
    InternalLogId logId, TimeProvider timeProvider) {
  Preconditions.checkNotNull(addressGroups, "addressGroups");
  Preconditions.checkArgument(!addressGroups.isEmpty(), "addressGroups is empty");
  checkListHasNoNulls(addressGroups, "addressGroups contains null entry");
  this.addressIndex = new Index(
      Collections.unmodifiableList(new ArrayList<>(addressGroups)));
  this.authority = authority;
  this.userAgent = userAgent;
  this.backoffPolicyProvider = backoffPolicyProvider;
  this.transportFactory = transportFactory;
  this.scheduledExecutor = scheduledExecutor;
  this.connectingTimer = stopwatchSupplier.get();
  this.syncContext = syncContext;
  this.callback = callback;
  this.channelz = channelz;
  this.callsTracer = callsTracer;
  this.channelTracer = Preconditions.checkNotNull(channelTracer, "channelTracer");
  this.logId = Preconditions.checkNotNull(logId, "logId");
  this.channelLogger = new ChannelLoggerImpl(channelTracer, timeProvider);
}
 
源代码6 项目: titus-control-plane   文件: TaskScenarioBuilder.java
public TaskScenarioBuilder moveTask(String targetJobId) {
    String taskId = getTask().getId();
    logger.info("[{}] Moving Task {} to another job {}", discoverActiveTest(), taskId, targetJobId);
    Stopwatch stopWatch = Stopwatch.createStarted();

    TestStreamObserver<Empty> responseObserver = new TestStreamObserver<>();
    jobClient.moveTask(TaskMoveRequest.newBuilder()
                    .setSourceJobId(jobScenarioBuilder.getJobId())
                    .setTargetJobId(targetJobId)
                    .setTaskId(taskId)
                    .build(),
            responseObserver);
    rethrow(() -> responseObserver.awaitDone(TIMEOUT_MS, TimeUnit.MILLISECONDS));

    logger.info("[{}] Task {} moved to job {} in {}[ms]", discoverActiveTest(), taskId, targetJobId, stopWatch.elapsed(TimeUnit.MILLISECONDS));
    return this;
}
 
public void awaitTime(long time, long timeoutMs) throws TimeoutException {
    System.out.println("Thread '" + Thread.currentThread().getName() + "' is waiting for time: " + time);

    Stopwatch stopWatch = Stopwatch.createStarted();
    Stopwatch showLifeSignStopWatch = Stopwatch.createStarted();

    while (internalTime.get() < time) {
        sleep_a_little_while();
        checkTimeout(timeoutMs, stopWatch);
        if (showLifeSignStopWatch.elapsed(TimeUnit.SECONDS) >= 1) {
            showLifeSignStopWatch = Stopwatch.createStarted();
            System.out.println("Thread '" + Thread.currentThread().getName() + "' is still waiting for time: " + time);
        }
    }

    System.out.println("Time " + time + " arrived for Thread '" + Thread.currentThread().getName() + "'");
}
 
源代码8 项目: metanome-algorithms   文件: FAIDACore.java
private List<SimpleInd> checkCandidates(List<SimpleInd> candidates) {
    Stopwatch sw = Stopwatch.createStarted();
    List<SimpleInd> result = new ArrayList<>();
    logger.info("checking: {} candidates on level {}", Integer.valueOf(candidates.size()),
    		Integer.valueOf(candidates.get(0).size()));
    int candidateCount = 0;
    for (SimpleInd candidate : candidates) {
        if (inclusionTester.isIncludedIn(candidate.left, candidate.right)) {
            result.add(candidate); // add result
        }
        candidateCount++;
        if ((candidates.size() > 1000 && candidateCount % (candidates.size() / 20) == 0) ||
                (candidates.size() <= 1000 && candidateCount % 100 == 0)) {
            logger.info("{}/{} candidates checked", Integer.valueOf(candidateCount), Integer.valueOf(candidates.size()));
        }
    }
    logger.info("Time checking candidates on level {}: {}ms, INDs found: {}",
    		Integer.valueOf(candidates.get(0).size()),
    		Long.valueOf(sw.elapsed(TimeUnit.MILLISECONDS)), Integer.valueOf(result.size()));
    return result;
}
 
源代码9 项目: elastic-db-tools-for-java   文件: PointMapping.java
/**
 * Performs validation that the local representation is as up-to-date as the representation on the backing data store.
 *
 * @param shardMap
 *            Shard map to which the shard provider belongs.
 * @param conn
 *            Connection used for validation.
 */
@Override
public void validate(StoreShardMap shardMap,
        Connection conn) {
    try {
        log.info("PointMapping Validate Start; Connection: {}", conn.getMetaData().getURL());
        Stopwatch stopwatch = Stopwatch.createStarted();

        ValidationUtils.validateMapping(conn, this.getShardMapManager(), shardMap, this.getStoreMapping());

        stopwatch.stop();

        log.info("PointMapping Validate Complete; Connection: {}; Duration:{}", conn.getMetaData().getURL(),
                stopwatch.elapsed(TimeUnit.MILLISECONDS));
    }
    catch (SQLException e) {
        e.printStackTrace();
        throw (ShardManagementException) e.getCause();
    }
}
 
源代码10 项目: rpcx-java   文件: CommonTest.java
@Test
public void testMap2() {
    ExecutorService pool = Executors.newFixedThreadPool(20);

    ConcurrentHashMap<String, String> m2 = new ConcurrentHashMap<>();
    m2.put("a", "1");

    Stopwatch sw2 = Stopwatch.createStarted();
    IntStream.range(0, 1000000).forEach(i -> {
        try {
            pool.invokeAll(IntStream.range(0, 20).mapToObj(ii -> (Callable<Void>) () -> {
                m2.get("a");
                return null;
            }).collect(Collectors.toList()));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    System.out.println(sw2.elapsed(TimeUnit.MILLISECONDS));

}
 
public void doTestPerformance(final int max) {
  final Procedure1<BuildRequest> _function = (BuildRequest it) -> {
    final Function1<Integer, URI> _function_1 = (Integer it_1) -> {
      return this.toFile((it_1).intValue(), max);
    };
    it.setDirtyFiles(IterableExtensions.<URI>toList(IterableExtensions.<Integer, URI>map(new IntegerRange(1, max), _function_1)));
  };
  final BuildRequest buildRequest = this.newBuildRequest(_function);
  final Stopwatch sw = Stopwatch.createStarted();
  this.build(buildRequest);
  StringConcatenation _builder = new StringConcatenation();
  _builder.append(max);
  _builder.append(" file took ");
  long _elapsed = sw.elapsed(TimeUnit.MILLISECONDS);
  _builder.append(_elapsed);
  _builder.append(" ms");
  InputOutput.<String>println(_builder.toString());
}
 
源代码12 项目: brooklyn-server   文件: TestSshCommandTest.java
@Test
public void shouldFailFastIfNoCommand() throws Exception {
    Duration longTimeout = Asserts.DEFAULT_LONG_TIMEOUT;
    
    Map<String, ?> equalsZero = ImmutableMap.of(EQUALS, 0);
    
    TestSshCommand test = app.createAndManageChild(EntitySpec.create(TestSshCommand.class)
            .configure(TIMEOUT, longTimeout.multiply(2))
            .configure(TARGET_ENTITY, testEntity)
            .configure(ASSERT_STATUS, makeAssertions(equalsZero)));

    Stopwatch stopwatch = Stopwatch.createStarted();
    try {
        app.start(ImmutableList.<Location>of());
        Asserts.shouldHaveFailedPreviously();
    } catch (Exception e) {
        // note: sleep(1000) can take a few millis less than 1000ms, according to a stopwatch.
        Asserts.expectedFailureContains(e, "Must specify exactly one of download.url and command");
        Duration elapsed = Duration.of(stopwatch);
        Asserts.assertTrue(elapsed.isShorterThan(longTimeout.subtract(Duration.millis(20))), "elapsed="+elapsed);
    }

    assertEntityFailed(test);
}
 
源代码13 项目: distributedlog   文件: BKLogWriteHandler.java
/**
 * Finalize a log segment. If the journal manager is currently
 * writing to a ledger, ensure that this is the ledger of the log segment
 * being finalized.
 * <p/>
 * Otherwise this is the recovery case. In the recovery case, ensure that
 * the firstTxId of the ledger matches firstTxId for the segment we are
 * trying to finalize.
 */
LogSegmentMetadata completeAndCloseLogSegment(String inprogressZnodeName, long logSegmentSeqNo,
                                              long ledgerId, long firstTxId, long lastTxId,
                                              int recordCount, long lastEntryId, long lastSlotId)
        throws IOException {
    Stopwatch stopwatch = Stopwatch.createStarted();
    boolean success = false;
    try {
        LogSegmentMetadata completedLogSegment =
                doCompleteAndCloseLogSegment(inprogressZnodeName, logSegmentSeqNo,
                        ledgerId, firstTxId, lastTxId, recordCount,
                        lastEntryId, lastSlotId);
        success = true;
        return completedLogSegment;
    } finally {
        if (success) {
            closeOpStats.registerSuccessfulEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS));
        } else {
            closeOpStats.registerFailedEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS));
        }
    }
}
 
源代码14 项目: elastic-db-tools-for-java   文件: ListShardMap.java
/**
 * Gets all the mappings that exist within given range and given shard.
 *
 * @param range
 *            Point value, any mapping overlapping with the range will be returned.
 * @param shard
 *            Shard for which the mappings will be returned.
 * @return Read-only collection of mappings that satisfy the given range and shard constraints.
 */
public List<PointMapping> getMappings(Range range,
        Shard shard) {
    ExceptionUtils.disallowNullArgument(range, "range");
    ExceptionUtils.disallowNullArgument(shard, "shard");

    try (ActivityIdScope activityIdScope = new ActivityIdScope(UUID.randomUUID())) {
        log.info("GetPointMappings", "Start; Shard: {}; Range:{}", shard.getLocation(), range);

        Stopwatch stopwatch = Stopwatch.createStarted();

        List<PointMapping> pointMappings = lsm.getMappingsForRange(range, shard, LookupOptions.LOOKUP_IN_STORE);

        stopwatch.stop();

        log.info("GetPointMappings", "Complete; Shard: {}; Range: {}; Duration:{}", shard.getLocation(),
                stopwatch.elapsed(TimeUnit.MILLISECONDS));

        return pointMappings;
    }
}
 
源代码15 项目: elastic-db-tools-for-java   文件: RangeShardMap.java
/**
 * Gets all the range mappings that exist within given range and given shard.
 *
 * @param range
 *            Range value, any mapping overlapping with the range will be returned.
 * @param shard
 *            Shard for which the mappings will be returned.
 * @return Read-only collection of mappings that satisfy the given range and shard constraints.
 */
public List<RangeMapping> getMappings(Range range,
        Shard shard) {
    ExceptionUtils.disallowNullArgument(range, "range");
    ExceptionUtils.disallowNullArgument(shard, "shard");

    try (ActivityIdScope activityIdScope = new ActivityIdScope(UUID.randomUUID())) {
        log.info("GetMappings Start; Shard: {}; Range: {}", shard.getLocation(), range);

        Stopwatch stopwatch = Stopwatch.createStarted();

        List<RangeMapping> rangeMappings = this.rsm.getMappingsForRange(range, shard, LookupOptions.LOOKUP_IN_STORE);

        stopwatch.stop();

        log.info("GetMappings Complete; Shard: {}; Duration: {}", shard.getLocation(), stopwatch.elapsed(TimeUnit.MILLISECONDS));

        return rangeMappings;
    }
}
 
源代码16 项目: brooklyn-library   文件: AbstractLoadTest.java
protected Callable<Entity> newProvisionAppTask(final String yaml) {
    return new Callable<Entity>() {
        public Entity call() throws Exception {
            try {
                Stopwatch stopwatch = Stopwatch.createStarted();
                Entity app = createAndStartApplication(yaml);
                Duration duration = Duration.of(stopwatch.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS);
                LOG.info("Provisioning time: "+duration);
                provisioningTimes.add(duration);

                return app;
            } catch (Throwable t) {
                LOG.error("Error deploying app (rethrowing)", t);
                throw Exceptions.propagate(t);
            }
        }
    };
}
 
源代码17 项目: mapr-music   文件: AlbumDao.java
/**
 * Returns number of albums according to the specified language.
 *
 * @param language language code.
 * @return number of albums with specified language code.
 */
public long getTotalNumByLanguage(String language) {
    return processStore((connection, store) -> {

        Stopwatch stopwatch = Stopwatch.createStarted();

        QueryCondition languageEqualsCondition = connection.newCondition()
                .is("language", QueryCondition.Op.EQUAL, language)
                .build();

        Query query = connection.newQuery()
                .select("_id")
                .where(languageEqualsCondition)
                .build();

        DocumentStream documentStream = store.findQuery(query);
        long totalNum = 0;
        for (Document ignored : documentStream) {
            totalNum++;
        }

        log.debug("Counting '{}' albums by language '{}' took {}", totalNum, language, stopwatch);

        return totalNum;
    });
}
 
源代码18 项目: bgpcep   文件: BGPPeer.java
@Override
public synchronized FluentFuture<? extends CommitInfo> releaseConnection() {
    LOG.info("Closing session with peer");
    this.sessionUp = false;
    this.adjRibOutListenerSet.values().forEach(AdjRibOutListener::close);
    this.adjRibOutListenerSet.clear();
    final FluentFuture<? extends CommitInfo> future;
    if (!isRestartingGracefully()) {
        future = terminateConnection();
    } else {
        final Set<TablesKey> gracefulTables = getGracefulTables();
        this.ribWriter.storeStaleRoutes(gracefulTables);
        future = this.ribWriter.clearTables(Sets.difference(this.tables, gracefulTables));
        if (isPeerRestarting()) {
            this.peerRestartStopwatch = Stopwatch.createStarted();
            handleRestartTimer();
        }
    }
    releaseBindingChain();

    closeSession();
    return future;
}
 
源代码19 项目: phoenix-tephra   文件: TransactionManager.java
public void abort(Transaction tx) {
  // guard against changes to the transaction log while processing
  txMetricsCollector.rate("abort");
  Stopwatch timer = new Stopwatch().start();
  this.logReadLock.lock();
  try {
    synchronized (this) {
      ensureAvailable();
      doAbort(tx.getTransactionId(), tx.getCheckpointWritePointers(), tx.getType());
    }
    appendToLog(TransactionEdit.createAborted(tx.getTransactionId(), tx.getType(), tx.getCheckpointWritePointers()));
    txMetricsCollector.histogram("abort.latency", (int) timer.elapsedMillis());
  } finally {
    this.logReadLock.unlock();
  }
}
 
源代码20 项目: bazel   文件: AndroidResourceParsingAction.java
public static void main(String[] args) throws Exception {
  OptionsParser optionsParser =
      OptionsParser.builder()
          .optionsClasses(Options.class, ResourceProcessorCommonOptions.class)
          .argsPreProcessor(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault()))
          .build();
  optionsParser.parseAndExitUponError(args);
  Options options = optionsParser.getOptions(Options.class);

  Preconditions.checkNotNull(options.primaryData);
  Preconditions.checkNotNull(options.output);

  final Stopwatch timer = Stopwatch.createStarted();
  ParsedAndroidData parsedPrimary = ParsedAndroidData.from(options.primaryData);
  logger.fine(String.format("Walked XML tree at %dms", timer.elapsed(TimeUnit.MILLISECONDS)));
  UnwrittenMergedAndroidData unwrittenData =
      UnwrittenMergedAndroidData.of(
          null, parsedPrimary, ParsedAndroidData.from(ImmutableList.<DependencyAndroidData>of()));
  AndroidDataSerializer serializer = AndroidDataSerializer.create();
  unwrittenData.serializeTo(serializer);
  serializer.flushTo(options.output);
  logger.fine(
      String.format("Finished parse + serialize in %dms", timer.elapsed(TimeUnit.MILLISECONDS)));
}
 
源代码21 项目: dremio-oss   文件: HiveVarcharTruncationReader.java
public void runProjector(BaseVariableWidthVector vector, int recordCount,
                         OperatorContext context,
                         Stopwatch javaCodeGenWatch,
                         Stopwatch gandivaCodeGenWatch) throws Exception {
  if (transferPair == null) {
    return;
  }

  if (castRequired(vector, recordCount, truncLen)) {
    splitter.projectRecords(recordCount, javaCodeGenWatch, gandivaCodeGenWatch);
    context.getStats().addLongStat(ScanOperator.Metric.TOTAL_HIVE_PARQUET_TRUNCATE_VARCHAR, 1);
  } else {
    javaCodeGenWatch.start();
    transferPair.transfer();
    javaCodeGenWatch.stop();
    context.getStats().addLongStat(ScanOperator.Metric.TOTAL_HIVE_PARQUET_TRANSFER_VARCHAR, 1);
  }
  context.getStats().addLongStat(ScanOperator.Metric.HIVE_PARQUET_CHECK_VARCHAR_CAST_TIME,
    varcharCheckCastWatch.elapsed(TimeUnit.NANOSECONDS));
  varcharCheckCastWatch.reset();
}
 
源代码22 项目: brooklyn-server   文件: ElectPrimaryTest.java
public static void main(String[] args) throws Exception {
        int count = -1;
        Stopwatch sw = Stopwatch.createStarted();
        while (++count<100) {
            log.info("new test run\n\n\nTEST RUN "+count+"\n");
            
//            ElectPrimaryTest t = new ElectPrimaryTest();
//            t.setUp();
//            t.testFireCausesPromoteDemote();
//            t.tearDown();
            
            TestNG testNG = new TestNG();
            testNG.setTestClasses(new Class[] { ElectPrimaryTest.class });
            testNG.addListener((ITestNGListener)new LoggingVerboseReporter());
            FailedReporter failedReporter = new FailedReporter();
            testNG.addListener((ITestNGListener)failedReporter);
            testNG.run();
            if (!failedReporter.getFailedTests().isEmpty()) {
                log.error("Failures: "+failedReporter.getFailedTests());
                System.exit(1);
            }
        }
        log.info("\n\nCompleted "+count+" runs in "+Duration.of(sw));
    }
 
源代码23 项目: bgpcep   文件: CheckTestUtil.java
private static <R, T extends DataObject> R readData(final DataBroker dataBroker, final LogicalDatastoreType ldt,
    final InstanceIdentifier<T> iid, final Function<T, R> function, final int timeout)
    throws ExecutionException, InterruptedException {
    AssertionError lastError = null;
    final Stopwatch sw = Stopwatch.createStarted();
    do {
        try (ReadTransaction tx = dataBroker.newReadOnlyTransaction()) {
            final Optional<T> data = tx.read(ldt, iid).get();
            if (data.isPresent()) {
                try {
                    return function.apply(data.get());
                } catch (final AssertionError e) {
                    lastError = e;
                    Uninterruptibles.sleepUninterruptibly(SLEEP_FOR, TimeUnit.MILLISECONDS);
                }
            }
        }
    } while (sw.elapsed(TimeUnit.SECONDS) <= timeout);
    throw lastError;
}
 
源代码24 项目: brooklyn-server   文件: TestWinrmCommandTest.java
@Test
public void shouldFailFastIfNoCommand() throws Exception {
    Duration longTimeout = Asserts.DEFAULT_LONG_TIMEOUT;
    
    Map<String, ?> equalsZero = ImmutableMap.of(EQUALS, 0);
    
    TestWinrmCommand test = app.createAndManageChild(EntitySpec.create(TestWinrmCommand.class)
            .configure(TIMEOUT, longTimeout.multiply(2))
            .configure(TARGET_ENTITY, testEntity)
            .configure(ASSERT_STATUS, makeAssertions(equalsZero)));

    Stopwatch stopwatch = Stopwatch.createStarted();
    try {
        app.start(ImmutableList.<Location>of());
        Asserts.shouldHaveFailedPreviously();
    } catch (Exception e) {
        // note: sleep(1000) can take a few millis less than 1000ms, according to a stopwatch.
        Asserts.expectedFailureContains(e, "Must specify exactly one of psScript and command");
        Duration elapsed = Duration.of(stopwatch);
        Asserts.assertTrue(elapsed.isShorterThan(longTimeout.subtract(Duration.millis(20))), "elapsed="+elapsed);
    }

    assertEntityFailed(test);
}
 
源代码25 项目: molgenis   文件: JsMagmaScriptEvaluatorTest.java
@Disabled
@Test
void testPerformance() {
  Entity person = new DynamicEntity(personBirthDateMeta);
  person.set("birthdate", now().atOffset(UTC).toLocalDate());

  jsMagmaScriptEvaluator.eval("$('birthdate').age().value()", person);

  Stopwatch sw = Stopwatch.createStarted();
  jsMagmaScriptEvaluator.eval(Collections.nCopies(10000, "$('birthdate').age().value()"), person);
  System.out.println(sw.elapsed(TimeUnit.MILLISECONDS) + " millis passed evalList");

  sw.reset().start();

  for (int i = 0; i < 10000; i++) {
    jsMagmaScriptEvaluator.eval("$('birthdate').age().value()", person);
  }
  System.out.println(
      sw.elapsed(TimeUnit.MILLISECONDS)
          + " millis passed recreating bindings for each evaluation");
}
 
源代码26 项目: emodb   文件: CassandraHealthCheck.java
private Result pingAll() {
    try {
        StringBuilder message = new StringBuilder();

        OperationResult<CqlStatementResult> astyanaxResult = pingAstyanax();
        message.append("Astyanax: ").append(astyanaxResult.getHost()).append(" ")
                .append(astyanaxResult.getLatency(TimeUnit.MICROSECONDS)).append("us");

        if (astyanaxResult.getAttemptsCount() != 1) {
            message.append(", ").append(astyanaxResult.getAttemptsCount()).append(" attempts");
        }

        Stopwatch cqlTimer = Stopwatch.createStarted();
        ResultSet cqlResult = pingCql();
        long queryDurationMicros = cqlTimer.elapsed(TimeUnit.MICROSECONDS);

        Host host = cqlResult.getExecutionInfo().getQueriedHost();
        message.append(" | CQL: ").append(host).append(" ").append(queryDurationMicros).append("us");

        return Result.healthy(message.toString());
    } catch (Throwable t) {
        return Result.unhealthy(t);
    }
}
 
private void freshPushVersionCache() {
    Stopwatch stopwatch = Stopwatch.createStarted();
    try {
        logger.info("fresh push version cache");
        List<PushConfigVersionItem> pushItems = pushConfigVersionDao.select();

        ConcurrentMap<Key, Version> newCache = new ConcurrentHashMap<Key, Version>(pushItems.size());
        for (PushConfigVersionItem pushItem : pushItems) {
            newCache.put(new Key(pushItem.getMeta(), pushItem.getIp()), new Version(pushItem.getVersion()));
        }

        this.cache = newCache;
        logger.info("fresh push version cache successOf, count [{}]", pushItems.size());
    } finally {
        Monitor.freshPushVersionCache.update(stopwatch.elapsed().toMillis(), TimeUnit.MILLISECONDS);
    }
}
 
源代码28 项目: brooklyn-server   文件: CountdownTimerTest.java
public void testNotify() throws InterruptedException {
    CountdownTimer timer = Duration.FIVE_SECONDS.countdownTimer();
    final Object mutex = new Object();
    final Semaphore gun = new Semaphore(0);
    Stopwatch watch = Stopwatch.createStarted();
    new Thread(new Runnable() {
        @Override
        public void run() {
            try { gun.acquire(); } catch (Exception e) { throw Exceptions.propagate(e); }
            synchronized (mutex) {
                mutex.notifyAll();
            }
        }
    }).start();
    synchronized (mutex) {
        gun.release();
        assertTrue(timer.waitOnForExpiry(mutex));
    }
    assertTrue(watch.elapsed(TimeUnit.MILLISECONDS) < 3000, "took too long: "+watch);
}
 
源代码29 项目: codebuff   文件: RateLimiter.java
public static final SleepingStopwatch createFromSystemTimer() {
  return new SleepingStopwatch() {
    final Stopwatch stopwatch = Stopwatch.createStarted();

    @Override
    protected long readMicros() {
      return stopwatch.elapsed(MICROSECONDS);
    }

    @Override
    protected void sleepMicrosUninterruptibly(long micros) {
      if (micros > 0) {
        Uninterruptibles.sleepUninterruptibly(micros, MICROSECONDS);
      }
    }
  };
}
 
源代码30 项目: distributedlog   文件: BKAsyncLogReaderDLSN.java
void setException(Throwable throwable) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    if (promise.updateIfEmpty(new Throw<List<LogRecordWithDLSN>>(throwable))) {
        futureSetLatency.registerFailedEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS));
        delayUntilPromiseSatisfied.registerFailedEvent(enqueueTime.elapsed(TimeUnit.MICROSECONDS));
    }
}