当前位置: 首页>>代码示例>>Java>>正文


Java Stopwatch类代码示例

本文整理汇总了Java中com.google.common.base.Stopwatch的典型用法代码示例。如果您正苦于以下问题:Java Stopwatch类的具体用法?Java Stopwatch怎么用?Java Stopwatch使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Stopwatch类属于com.google.common.base包,在下文中一共展示了Stopwatch类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: verifyActorReady

import com.google.common.base.Stopwatch; //导入依赖的package包/类
@SuppressWarnings("checkstyle:IllegalCatch")
private void verifyActorReady(ActorRef actorRef) {
    // Sometimes we see messages go to dead letters soon after creation - it seems the actor isn't quite
    // in a state yet to receive messages or isn't actually created yet. This seems to happen with
    // actorSelection so, to alleviate it, we use an actorSelection and send an Identify message with
    // retries to ensure it's ready.

    Timeout timeout = new Timeout(100, TimeUnit.MILLISECONDS);
    Throwable lastError = null;
    Stopwatch sw = Stopwatch.createStarted();
    while (sw.elapsed(TimeUnit.SECONDS) <= 10) {
        try {
            ActorSelection actorSelection = system.actorSelection(actorRef.path().toString());
            Future<Object> future = Patterns.ask(actorSelection, new Identify(""), timeout);
            ActorIdentity reply = (ActorIdentity)Await.result(future, timeout.duration());
            Assert.assertNotNull("Identify returned null", reply.getRef());
            return;
        } catch (Exception | AssertionError e) {
            Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
            lastError = e;
        }
    }

    throw new RuntimeException(lastError);
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:26,代码来源:TestActorFactory.java

示例2: deleteMapping

import com.google.common.base.Stopwatch; //导入依赖的package包/类
/**
 * Removes a range mapping.
 *
 * @param mapping
 *            Mapping being removed.
 * @param mappingLockToken
 *            An instance of <see cref="MappingLockToken"/>
 */
public void deleteMapping(RangeMapping mapping,
        MappingLockToken mappingLockToken) {
    ExceptionUtils.disallowNullArgument(mapping, "mapping");
    ExceptionUtils.disallowNullArgument(mappingLockToken, "mappingLockToken");

    try (ActivityIdScope activityIdScope = new ActivityIdScope(UUID.randomUUID())) {
        log.info("DeleteMapping Start; Shard: {}", mapping.getShard().getLocation());

        Stopwatch stopwatch = Stopwatch.createStarted();

        this.rsm.remove(mapping, mappingLockToken.getLockOwnerId());

        stopwatch.stop();

        log.info("DeleteMapping Complete; Shard: {}; Duration: {}", mapping.getShard().getLocation(), stopwatch.elapsed(TimeUnit.MILLISECONDS));
    }
}
 
开发者ID:Microsoft,项目名称:elastic-db-tools-for-java,代码行数:26,代码来源:RangeShardMap.java

示例3: verifyShardState

import com.google.common.base.Stopwatch; //导入依赖的package包/类
public static void verifyShardState(final AbstractDataStore datastore, final String shardName,
        final Consumer<OnDemandShardState> verifier) throws Exception {
    ActorContext actorContext = datastore.getActorContext();

    Future<ActorRef> future = actorContext.findLocalShardAsync(shardName);
    ActorRef shardActor = Await.result(future, Duration.create(10, TimeUnit.SECONDS));

    AssertionError lastError = null;
    Stopwatch sw = Stopwatch.createStarted();
    while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
        OnDemandShardState shardState = (OnDemandShardState)actorContext
                .executeOperation(shardActor, GetOnDemandRaftState.INSTANCE);

        try {
            verifier.accept(shardState);
            return;
        } catch (AssertionError e) {
            lastError = e;
            Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
        }
    }

    throw lastError;
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:25,代码来源:IntegrationTestKit.java

示例4: initNotificationManager

import com.google.common.base.Stopwatch; //导入依赖的package包/类
private void initNotificationManager() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        final Stopwatch watch = Stopwatch.createStarted();
        final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        final NotificationChannel received = new NotificationChannel(Constants.NOTIFICATION_CHANNEL_ID_RECEIVED,
                getString(R.string.notification_channel_received_name), NotificationManager.IMPORTANCE_DEFAULT);
        received.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.coins_received),
                new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                        .setLegacyStreamType(AudioManager.STREAM_NOTIFICATION)
                        .setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT).build());
        nm.createNotificationChannel(received);

        final NotificationChannel ongoing = new NotificationChannel(Constants.NOTIFICATION_CHANNEL_ID_ONGOING,
                getString(R.string.notification_channel_ongoing_name), NotificationManager.IMPORTANCE_LOW);
        nm.createNotificationChannel(ongoing);

        final NotificationChannel important = new NotificationChannel(Constants.NOTIFICATION_CHANNEL_ID_IMPORTANT,
                getString(R.string.notification_channel_important_name), NotificationManager.IMPORTANCE_HIGH);
        nm.createNotificationChannel(important);

        log.info("created notification channels, took {}", watch);
    }
}
 
开发者ID:guodroid,项目名称:okwallet,代码行数:25,代码来源:WalletApplication.java

示例5: getTotalNumByLanguage

import com.google.common.base.Stopwatch; //导入依赖的package包/类
/**
 * 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;
    });
}
 
开发者ID:mapr-demos,项目名称:mapr-music,代码行数:32,代码来源:AlbumDao.java

示例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();
  }
}
 
开发者ID:dremio,项目名称:dremio-oss,代码行数:22,代码来源:EventLoopCloseable.java

示例7: 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;
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:18,代码来源:AbstractEntityOwnershipTest.java

示例8: getByUserId

import com.google.common.base.Stopwatch; //导入依赖的package包/类
/**
 * Returns list of Artist rates by user identifier.
 *
 * @param userId user's identifier.
 * @return list of Artist rates.
 */
public List<ArtistRate> getByUserId(String userId) {
    return processStore((connection, store) -> {

        Stopwatch stopwatch = Stopwatch.createStarted();
        Query query = connection.newQuery().where(
                connection.newCondition()
                        .is("user_id", QueryCondition.Op.EQUAL, userId)
                        .build()
        ).build();

        // Fetch all OJAI Documents from this store according to the built query
        DocumentStream documentStream = store.findQuery(query);
        List<ArtistRate> rates = new ArrayList<>();
        for (Document document : documentStream) {
            ArtistRate rate = mapOjaiDocument(document);
            if (rate != null) {
                rates.add(rate);
            }
        }

        log.debug("Get '{}' rates by user id '{}' took {}", rates.size(), userId, stopwatch);

        return rates;
    });
}
 
开发者ID:mapr-demos,项目名称:mapr-music,代码行数:32,代码来源:ArtistRateDao.java

示例9: getByArtistId

import com.google.common.base.Stopwatch; //导入依赖的package包/类
/**
 * Returns list of Artist rates by artist identifier.
 *
 * @param artistId artist's identifier.
 * @return list of Artist rates.
 */
public List<ArtistRate> getByArtistId(String artistId) {
    return processStore((connection, store) -> {

        Stopwatch stopwatch = Stopwatch.createStarted();
        Query query = connection.newQuery().where(
                connection.newCondition()
                        .is("document_id", QueryCondition.Op.EQUAL, artistId)
                        .build()
        ).build();

        // Fetch all OJAI Documents from this store according to the built query
        DocumentStream documentStream = store.findQuery(query);
        List<ArtistRate> rates = new ArrayList<>();
        for (Document document : documentStream) {
            ArtistRate rate = mapOjaiDocument(document);
            if (rate != null) {
                rates.add(rate);
            }
        }

        log.debug("Get '{}' rates by artist id '{}' took {}", rates.size(), artistId, stopwatch);

        return rates;
    });
}
 
开发者ID:mapr-demos,项目名称:mapr-music,代码行数:32,代码来源:ArtistRateDao.java

示例10: getMappings

import com.google.common.base.Stopwatch; //导入依赖的package包/类
/**
 * Gets all the range mappings that exist within given range.
 *
 * @param range
 *            Range value, any mapping overlapping with the range will be returned.
 * @param lookupOptions
 *            Whether to search in the cache and/or store.
 * @return Read-only collection of mappings that satisfy the given range constraint.
 */
public List<RangeMapping> getMappings(Range range,
        LookupOptions lookupOptions) {
    ExceptionUtils.disallowNullArgument(range, "range");

    try (ActivityIdScope activityIdScope = new ActivityIdScope(UUID.randomUUID())) {
        log.info("GetMappings Start; Range: {}; Lookup Options: {}", range, lookupOptions);

        Stopwatch stopwatch = Stopwatch.createStarted();

        List<RangeMapping> rangeMappings = this.rsm.getMappingsForRange(range, null, lookupOptions);

        stopwatch.stop();

        log.info("GetMappings Complete; Range: {}; Lookup Options: {}; Duration: {}", range, lookupOptions,
                stopwatch.elapsed(TimeUnit.MILLISECONDS));

        return rangeMappings;
    }
}
 
开发者ID:Microsoft,项目名称:elastic-db-tools-for-java,代码行数:29,代码来源:RangeShardMap.java

示例11: getFragments

import com.google.common.base.Stopwatch; //导入依赖的package包/类
/**
 * Generate a set of assigned fragments based on the provided fragment tree. Do not allow parallelization stages
 * to go beyond the global max width.
 *
 * @param options         Option list
 * @param foremanNode     The driving/foreman node for this query.  (this node)
 * @param queryId         The queryId for this query.
 * @param activeEndpoints The list of endpoints to consider for inclusion in planning this query.
 * @param reader          Tool used to read JSON plans
 * @param rootFragment    The root node of the PhysicalPlan that we will be parallelizing.
 * @param session         UserSession of user who launched this query.
 * @param queryContextInfo Info related to the context when query has started.
 * @return The list of generated PlanFragment protobuf objects to be assigned out to the individual nodes.
 * @throws ExecutionSetupException
 */
public List<PlanFragment> getFragments(
    OptionList options,
    NodeEndpoint foremanNode,
    QueryId queryId,
    Collection<NodeEndpoint> activeEndpoints,
    PhysicalPlanReader reader,
    Fragment rootFragment,
    UserSession session,
    QueryContextInformation queryContextInfo,
    FunctionLookupContext functionLookupContext) throws ExecutionSetupException {
  observer.planParallelStart();
  final Stopwatch stopwatch = Stopwatch.createStarted();
  final PlanningSet planningSet = getFragmentsHelper(activeEndpoints, rootFragment);
  observer.planParallelized(planningSet);
  stopwatch.stop();
  observer.planAssignmentTime(stopwatch.elapsed(TimeUnit.MILLISECONDS));
  stopwatch.start();
  List<PlanFragment> fragments = generateWorkUnit(options, foremanNode, queryId, reader, rootFragment, planningSet, session, queryContextInfo, functionLookupContext);
  stopwatch.stop();
  observer.planGenerationTime(stopwatch.elapsed(TimeUnit.MILLISECONDS));
  observer.plansDistributionComplete(new QueryWorkUnit(fragments));
  return fragments;
}
 
开发者ID:dremio,项目名称:dremio-oss,代码行数:39,代码来源:SimpleParallelizer.java

示例12: update

import com.google.common.base.Stopwatch; //导入依赖的package包/类
/**
 * {@inheritDoc}
 *
 * @param id        identifier of document, which will be updated.
 * @param albumRate album rate.
 * @return updated album rate.
 */
@Override
public AlbumRate update(String id, AlbumRate albumRate) {
    return processStore((connection, store) -> {

        Stopwatch stopwatch = Stopwatch.createStarted();

        // Create a DocumentMutation to update non-null fields
        DocumentMutation mutation = connection.newMutation();

        // Update only non-null fields
        if (albumRate.getRating() != null) {
            mutation.set("rating", albumRate.getRating());
        }

        // Update the OJAI Document with specified identifier
        store.update(id, mutation);

        Document updatedOjaiDoc = store.findById(id);

        log.debug("Update document from table '{}' with id: '{}'. Elapsed time: {}", tablePath, id, stopwatch);

        // Map Ojai document to the actual instance of model class
        return mapOjaiDocument(updatedOjaiDoc);
    });
}
 
开发者ID:mapr-demos,项目名称:mapr-music,代码行数:33,代码来源:AlbumRateDao.java

示例13: createPointMapping

import com.google.common.base.Stopwatch; //导入依赖的package包/类
/**
 * Creates and adds a point mapping to ShardMap.
 *
 * @param point
 *            Point for which to create the mapping.
 * @param shard
 *            Shard associated with the point mapping.
 * @return Newly created mapping.
 */
public PointMapping createPointMapping(KeyT point,
        Shard shard) {
    ExceptionUtils.disallowNullArgument(shard, "shard");

    try (ActivityIdScope activityIdScope = new ActivityIdScope(UUID.randomUUID())) {
        PointMappingCreationInfo args = new PointMappingCreationInfo(point, shard, MappingStatus.Online);

        String mappingKey = args.getKey().toString();
        log.info("CreatePointMapping Start; ShardMap name: {}; Point Mapping: {}", this.getName(), mappingKey);

        Stopwatch stopwatch = Stopwatch.createStarted();

        PointMapping pointMapping = lsm.add(new PointMapping(this.getShardMapManager(), args));

        stopwatch.stop();

        log.info("CreatePointMapping Complete; ShardMap name: {}; Point Mapping: {}; Duration: {}", this.getName(), mappingKey,
                stopwatch.elapsed(TimeUnit.MILLISECONDS));

        return pointMapping;
    }
}
 
开发者ID:Microsoft,项目名称:elastic-db-tools-for-java,代码行数:32,代码来源:ListShardMap.java

示例14: testFull

import com.google.common.base.Stopwatch; //导入依赖的package包/类
private void testFull(QueryType type, String planText, String filename,
    int numberOfTimesRead /* specified in json plan */,
    int numberOfRowGroups, int recordsPerRowGroup, boolean testValues) throws Exception {

  // final RecordBatchLoader batchLoader = new RecordBatchLoader(getAllocator());
  final HashMap<String, FieldInfo> fields = new HashMap<>();
  final ParquetTestProperties props =
      new ParquetTestProperties(numberRowGroups, recordsPerRowGroup, DEFAULT_BYTES_PER_PAGE, fields);
  TestFileGenerator.populateFieldInfoMap(props);
  final ParquetResultListener resultListener =
      new ParquetResultListener(getAllocator(), props, numberOfTimesRead, testValues);
  final Stopwatch watch = Stopwatch.createStarted();
  testWithListener(type, planText, resultListener);
  resultListener.getResults();
  // batchLoader.clear();
  System.out.println(String.format("Took %d ms to run query", watch.elapsed(TimeUnit.MILLISECONDS)));
}
 
开发者ID:dremio,项目名称:dremio-oss,代码行数:18,代码来源:ParquetRecordReaderTest.java

示例15: deleteMapping

import com.google.common.base.Stopwatch; //导入依赖的package包/类
/**
 * Removes a point mapping.
 *
 * @param mapping
 *            Mapping being removed.
 */
public void deleteMapping(PointMapping mapping) {
    ExceptionUtils.disallowNullArgument(mapping, "mapping");

    try (ActivityIdScope activityIdScope = new ActivityIdScope(UUID.randomUUID())) {
        String mappingKey = mapping.getKey().getRawValue().toString();
        log.info("DeletePointMapping Start; ShardMap name: {}; Point Mapping: {}", this.getName(), mappingKey);

        Stopwatch stopwatch = Stopwatch.createStarted();

        lsm.remove(mapping);

        stopwatch.stop();

        log.info("DeletePointMapping Completed; ShardMap name: {}; Point Mapping: {}; Duration: {}", this.getName(), mappingKey,
                stopwatch.elapsed(TimeUnit.MILLISECONDS));
    }
}
 
开发者ID:Microsoft,项目名称:elastic-db-tools-for-java,代码行数:24,代码来源:ListShardMap.java


注:本文中的com.google.common.base.Stopwatch类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。