Example usage for com.google.common.base Stopwatch stop

List of usage examples for com.google.common.base Stopwatch stop

Introduction

In this page you can find the example usage for com.google.common.base Stopwatch stop.

Prototype

public Stopwatch stop() 

Source Link

Document

Stops the stopwatch.

Usage

From source file:org.bitcoinj.params.AbstractBitcoinNetParams.java

@Override
public void checkDifficultyTransitions(final StoredBlock storedPrev, final Block nextBlock,
        final BlockStore blockStore) throws VerificationException, BlockStoreException {
    final Block prev = storedPrev.getHeader();

    // Is this supposed to be a difficulty transition point?
    if (!isDifficultyTransitionPoint(storedPrev.getHeight())) {

        // No ... so check the difficulty didn't actually change.
        if (nextBlock.getDifficultyTarget() != prev.getDifficultyTarget())
            throw new VerificationException("Unexpected change in difficulty at height "
                    + storedPrev.getHeight() + ": " + Long.toHexString(nextBlock.getDifficultyTarget()) + " vs "
                    + Long.toHexString(prev.getDifficultyTarget()));
        return;/*www. jav  a2s  .com*/
    }

    // We need to find a block far back in the chain. It's OK that this is expensive because it only occurs every
    // two weeks after the initial block chain download.
    final Stopwatch watch = Stopwatch.createStarted();
    Sha256Hash hash = prev.getHash();
    StoredBlock cursor = null;
    final int interval = this.getInterval();
    for (int i = 0; i < interval; i++) {
        cursor = blockStore.get(hash);
        if (cursor == null) {
            // This should never happen. If it does, it means we are following an incorrect or busted chain.
            throw new VerificationException(
                    "Difficulty transition point but we did not find a way back to the last transition point. Not found: "
                            + hash);
        }
        hash = cursor.getHeader().getPrevBlockHash();
    }
    checkState(cursor != null && isDifficultyTransitionPoint(cursor.getHeight() - 1),
            "Didn't arrive at a transition point.");
    watch.stop();
    if (watch.elapsed(TimeUnit.MILLISECONDS) > 50)
        log.info("Difficulty transition traversal took {}", watch);

    Block blockIntervalAgo = cursor.getHeader();
    int timespan = (int) (prev.getTimeSeconds() - blockIntervalAgo.getTimeSeconds());
    // Limit the adjustment step.
    final int targetTimespan = this.getTargetTimespan();
    if (timespan < targetTimespan / 4)
        timespan = targetTimespan / 4;
    if (timespan > targetTimespan * 4)
        timespan = targetTimespan * 4;

    BigInteger newTarget = Utils.decodeCompactBits(prev.getDifficultyTarget());
    newTarget = newTarget.multiply(BigInteger.valueOf(timespan));
    newTarget = newTarget.divide(BigInteger.valueOf(targetTimespan));

    if (newTarget.compareTo(this.getMaxTarget()) > 0) {
        log.info("Difficulty hit proof of work limit: {}", newTarget.toString(16));
        newTarget = this.getMaxTarget();
    }

    int accuracyBytes = (int) (nextBlock.getDifficultyTarget() >>> 24) - 3;
    long receivedTargetCompact = nextBlock.getDifficultyTarget();

    // The calculated difficulty is to a higher precision than received, so reduce here.
    BigInteger mask = BigInteger.valueOf(0xFFFFFFL).shiftLeft(accuracyBytes * 8);
    newTarget = newTarget.and(mask);
    long newTargetCompact = Utils.encodeCompactBits(newTarget);

    if (newTargetCompact != receivedTargetCompact)
        throw new VerificationException("Network provided difficulty bits do not match what was calculated: "
                + Long.toHexString(newTargetCompact) + " vs " + Long.toHexString(receivedTargetCompact));
}

From source file:dk.dma.nogoservice.service.S3DataLoader.java

<T> T loadData(String key, Class<T> clazz) throws IOException {
    Stopwatch stopwatch = Stopwatch.createStarted();
    S3Object object = amazonS3.getObject(S3DataLoader.DATA_BUCKET, key);

    File cacheFile = new File(tempDir, object.getObjectMetadata().getETag() + key);
    ObjectMapper objectMapper = new ObjectMapper();
    if (cacheLocally) {
        if (cacheFile.exists()) {
            log.info("Using local cached file {}", cacheFile.getAbsolutePath());
            return objectMapper.readValue(cacheFile, clazz);
        }/*from   w w w. j  a  va 2s.c  o m*/
    }

    try (S3ObjectInputStream objectContent = object.getObjectContent()) {
        T data = objectMapper.readValue(objectContent, clazz);
        if (cacheLocally) {
            log.info("caching S3 file locally in {}", cacheFile.getAbsolutePath());
            objectMapper.writeValue(cacheFile, data);
        }
        return data;
    } finally {
        log.info("Loaded file {} from Amazon S3 in {} ms", key,
                stopwatch.stop().elapsed(TimeUnit.MILLISECONDS));
    }
}

From source file:org.jboss.hal.meta.processing.UpdateDatabaseTask.java

@SuppressWarnings("unchecked")
public Completable call(LookupContext context) {
    if (context.updateDatabase()) {
        Stopwatch watch = Stopwatch.createStarted();
        for (Map.Entry<ResourceAddress, ResourceDescription> entry : context.toResourceDescriptionDatabase
                .entrySet()) {//from w  ww . j  a  v  a2s  .  c o m
            ResourceAddress address = entry.getKey();
            ResourceDescription resourceDescription = entry.getValue();
            workerChannel.postResourceDescription(address, resourceDescription, context.recursive);
        }
        for (Map.Entry<ResourceAddress, SecurityContext> entry : context.toSecurityContextDatabase.entrySet()) {
            ResourceAddress address = entry.getKey();
            SecurityContext securityContext = entry.getValue();
            workerChannel.postSecurityContext(address, securityContext, context.recursive);
        }
        logger.debug("Posted {} resource descriptions and {} security contexts to the databases in {} ms",
                context.toResourceDescriptionDatabase.size(), context.toSecurityContextDatabase.size(),
                watch.stop().elapsed(MILLISECONDS));
    }
    return Completable.complete();
}

From source file:org.activityinfo.server.endpoint.gwtrpc.AdvisoryLock.java

public AdvisoryLock(HibernateEntityManager entityManager) {
    Preconditions.checkNotNull(entityManager);

    this.entityManager = entityManager;

    try {/* www  .  j  av a 2 s  .  com*/
        Stopwatch stopwatch = Stopwatch.createStarted();

        String sql = String.format("SELECT GET_LOCK('%s', %s)", ADVISORY_LOCK_NAME, ADVISORY_GET_LOCK_TIMEOUT);

        Query query = entityManager.getSession().createSQLQuery(sql);
        Object result = query.uniqueResult();

        if (result == null) {
            throw new UnexpectedCommandException("Error occurred while trying to obtain advisory lock.");
        }

        int resultCode = ((Number) result).intValue();
        if (resultCode == TIMEOUT_CODE) { // time out
            LOGGER.severe("Timed out waiting for write lock.");
            throw new CommandTimeoutException();
        }

        if (resultCode != SUCCESS_CODE) { // not success
            LOGGER.severe("Failed to acquire lock, result code: " + resultCode);
            throw new RuntimeException("Failed to acquire lock, result code: " + resultCode);
        }

        stopwatch.stop();
        LOGGER.finest("Acquiring advisory lock takes: " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "ms");
    } catch (CommandTimeoutException e) {
        throw e;
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Internal error during acquiring advisory lock: " + e.getMessage(), e);
        throw new RuntimeException("Exception caught while trying to acquire update lock", e);
    }
}

From source file:de.schildbach.wallet.WalletApplication.java

public void backupWallet() {
    final Stopwatch watch = Stopwatch.createStarted();
    final Protos.Wallet.Builder builder = new WalletProtobufSerializer().walletToProto(wallet).toBuilder();

    // strip redundant
    builder.clearTransaction();/*from  w  w w . j  a  v a 2  s. c om*/
    builder.clearLastSeenBlockHash();
    builder.setLastSeenBlockHeight(-1);
    builder.clearLastSeenBlockTimeSecs();
    final Protos.Wallet walletProto = builder.build();

    OutputStream os = null;

    try {
        os = openFileOutput(Constants.Files.WALLET_KEY_BACKUP_PROTOBUF, Context.MODE_PRIVATE);
        walletProto.writeTo(os);
        watch.stop();
        log.info("wallet backed up to: '{}', took {}", Constants.Files.WALLET_KEY_BACKUP_PROTOBUF, watch);
    } catch (final IOException x) {
        log.error("problem writing wallet backup", x);
    } finally {
        try {
            os.close();
        } catch (final IOException x) {
            // swallow
        }
    }
}

From source file:org.jenkinsci.plugins.relution_publisher.builder.ArtifactFileUploader.java

private JsonObject uploadAsset(final File directory, final String fileName)
        throws URISyntaxException, InterruptedException {

    try {// w w  w .j  a  v a2s .  c om
        final Stopwatch sw = new Stopwatch();
        final File file = new File(directory, fileName);
        final ApiRequest request = RequestFactory.createUploadRequest(this.store, file);

        this.log.write(this, "Uploading \"%s\" (%,d Byte)", fileName, file.length());

        sw.start();
        final ApiResponse response = this.requestManager.execute(request, this.log);
        sw.stop();

        final String speed = this.getUploadSpeed(sw, file);
        this.log.write(this, "Upload of file completed (%s, %s).", sw, speed);

        return this.extractAsset(response);

    } catch (final IOException e) {
        this.log.write(this, "Upload of file failed, error during execution:\n\n%s\n", e);
        Builds.setResult(this, Result.UNSTABLE, this.log);

    } catch (final ExecutionException e) {
        this.log.write(this, "Upload of file failed, error during execution:\n\n%s\n", e);
        Builds.setResult(this, Result.UNSTABLE, this.log);

    }
    return null;
}

From source file:at.sti2.sparkwave.parser.StreamParserThread.java

public void run() {

    long tripleCounter = 0;

    try {//ww w  . jav a  2 s  .  c  om

        Stopwatch stopWatch = new Stopwatch();
        stopWatch.start();

        while (run) {

            // Get triple from the stream
            Triple triple = getTriple();
            tripleCounter++;

            if (!triple.isPoisonTriple()) {

                long currentTimeMillis = System.currentTimeMillis();
                triple.setTimestamp(currentTimeMillis);

                //synchronized because it might happen that SparkwaveKernel thread removes a queue from queues
                synchronized (queues) {
                    // put triple in all queues
                    for (BlockingQueue<Triple> queue : queues) {
                        queue.put(triple);
                    }
                }
            } else {
                run = false;
            }
        }

        stopWatch.stop();

        StringBuffer timeBuffer = new StringBuffer();
        timeBuffer.append("Streaming took [" + stopWatch.elapsedTime(TimeUnit.MILLISECONDS) + "ms] ");
        timeBuffer.append(stopWatch.elapsedTime(TimeUnit.MINUTES));
        timeBuffer.append(" min ");
        timeBuffer.append(stopWatch.elapsedTime(TimeUnit.SECONDS));
        timeBuffer.append(" s ");
        timeBuffer.append(stopWatch.elapsedTime(TimeUnit.MILLISECONDS));
        timeBuffer.append(" ms.");

        logger.info(timeBuffer.toString());
        logger.info("Processed " + tripleCounter + " triples.");
        //         logger.info("Pattern has been matched "+ sparkwaveNetwork.getReteNetwork().getNumMatches()+ " times.");

    } catch (InterruptedException e) {
        logger.error(e.getMessage());
    }
}

From source file:com.thinkbiganalytics.feedmgr.nifi.CreateFeedBuilder.java

/**
 * Updates a process groups properties//from   w w w .j a  va  2s .c o m
 */
private void updateProcessGroupProperties(String processGroupId, String processGroupName)
        throws FeedCreationException {
    Stopwatch stopwatch = Stopwatch.createStarted();
    List<NifiProperty> propertiesToUpdate = restClient.getPropertiesForProcessGroup(processGroupId);
    stopwatch.stop();
    log.debug("Time to get Properties in Feed updateProcessGroupProperties: {} ms",
            stopwatch.elapsed(TimeUnit.MILLISECONDS));

    stopwatch.reset();
    stopwatch.start();
    //get the Root processGroup
    ProcessGroupDTO rootProcessGroup = niFiObjectCache.getRootProcessGroup();
    stopwatch.stop();
    log.debug("Time to get root Process Group in updateProcessGroupProperties: {} ms",
            stopwatch.elapsed(TimeUnit.MILLISECONDS));
    stopwatch.reset();

    stopwatch.start();
    modifiedProperties = new ArrayList<>();
    //resolve the static properties
    //first fill in any properties with static references
    List<NifiProperty> modifiedStaticProperties = propertyExpressionResolver
            .resolveStaticProperties(propertiesToUpdate);
    // now apply any of the incoming metadata properties to this

    List<NifiProperty> modifiedFeedMetadataProperties = NifiPropertyUtil.matchAndSetPropertyValues(
            rootProcessGroup.getName(), processGroupName, propertiesToUpdate, properties);
    modifiedProperties.addAll(modifiedStaticProperties);
    modifiedProperties.addAll(modifiedFeedMetadataProperties);

    stopwatch.stop();
    log.debug("Time to set modifiedProperties: {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
    stopwatch.reset();

    stopwatch.start();
    restClient.updateProcessGroupProperties(modifiedProperties);
    stopwatch.stop();
    log.debug("Time to update properties in the process group: {} ms",
            stopwatch.elapsed(TimeUnit.MILLISECONDS));

}

From source file:com.vmware.photon.controller.rootscheduler.xenon.task.PlacementTaskService.java

/**
 * Returns the best host selected host among successful responses. If there are not any hosts to place the request,
 * this returns a result from the host responses.
 *
 * @param okResponses// www .j a v  a2s.  c  om
 * @param allResponses
 * @param currentState
 * @param watch
 * @return
 */
private PlacementTask selectBestResponse(Set<PlaceResponse> okResponses, Set<PlaceResponse> allResponses,
        PlacementTask currentState, Stopwatch watch) {
    SchedulerServiceGroup scheduler = (SchedulerServiceGroup) ((PhotonControllerXenonHost) getHost())
            .getScheduler();
    ScoreCalculator scoreCalculator = scheduler.getScoreCalculator();
    PlaceResponse response = scoreCalculator.pickBestResponse(okResponses);
    watch.stop();

    PlacementTask patchState;
    if (response == null) {
        PlaceResultCode errorCode;
        String errorMsg;
        Set<PlaceResultCode> returnCodes;

        returnCodes = allResponses.stream().map(r -> {
            return r.getResult();
        }).collect(Collectors.toSet());

        if (returnCodes.contains(PlaceResultCode.NOT_ENOUGH_CPU_RESOURCE)) {
            errorCode = PlaceResultCode.NOT_ENOUGH_CPU_RESOURCE;
            errorMsg = "Not enough cpu resources available";
        } else if (returnCodes.contains(PlaceResultCode.NOT_ENOUGH_MEMORY_RESOURCE)) {
            errorCode = PlaceResultCode.NOT_ENOUGH_MEMORY_RESOURCE;
            errorMsg = "Not enough memory resources available";
        } else if (returnCodes.contains((PlaceResultCode.NOT_ENOUGH_DATASTORE_CAPACITY))) {
            errorCode = PlaceResultCode.NOT_ENOUGH_DATASTORE_CAPACITY;
            errorMsg = "Not enough capacity in the datastore available";
        } else if (returnCodes.contains(PlaceResultCode.NO_SUCH_RESOURCE)) {
            errorCode = PlaceResultCode.NO_SUCH_RESOURCE;
            errorMsg = "No such resource";
        } else if (returnCodes.contains(PlaceResultCode.INVALID_STATE)) {
            errorCode = PlaceResultCode.INVALID_STATE;
            errorMsg = "Agent in an invalid state";
        } else {
            errorCode = PlaceResultCode.SYSTEM_ERROR;
            errorMsg = String.format("Received no response in %d ms", watch.elapsed(TimeUnit.MILLISECONDS));
        }
        patchState = buildPatch(TaskState.TaskStage.FAILED, currentState.taskState.isDirect, null);
        patchState.resultCode = errorCode;
        patchState.error = errorMsg;
        ServiceUtils.logWarning(this, "Placement failure reasons: %s", genJsonErrorSummary(allResponses));
    } else {
        patchState = buildPatch(TaskState.TaskStage.FINISHED, currentState.taskState.isDirect, null);
        ServiceUtils.logInfo(this, "Returning bestResponse: %s in %d ms", response,
                watch.elapsed(TimeUnit.MILLISECONDS));
        patchState.resultCode = response.getResult();
        patchState.generation = response.getGeneration();
        patchState.serverAddress = response.getAddress();
        patchState.resource = new Resource();
        patchState.resource.setPlacement_list(response.getPlacementList());
    }
    return patchState;
}

From source file:com.facebook.buck.parser.cache.impl.LocalCacheStorage.java

@Override
public Optional<BuildFileManifest> getBuildFileManifest(HashCode weakFingerprint, HashCode strongFingerprint)
        throws IOException {
    Stopwatch timer = null;
    if (LOG.isVerboseEnabled()) {
        timer = Stopwatch.createStarted();
    }//from   w  w  w.j  av  a2s . c  om

    try {
        if (!isReadAllowed()) {
            return Optional.empty();
        }

        Path cachedBuildFileManifestPath = filesystem.resolve(localCachePath)
                .resolve(weakFingerprint.toString()).resolve(strongFingerprint.toString());

        byte[] data;
        try {
            // TODO(buck_team): Add readAllBytes to projectFileSystem and use it
            data = Files.readAllBytes(cachedBuildFileManifestPath);
        } catch (NoSuchFileException ex) {
            return Optional.empty();
        }

        return Optional.of(BuildFileManifestSerializer.deserialize(data));
    } finally {
        if (timer != null) {
            LOG.verbose("Time to complete getBuildFileManifest: %d ns.",
                    timer.stop().elapsed(TimeUnit.NANOSECONDS));
        }
    }
}