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

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

Introduction

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

Prototype

@CheckReturnValue
public long elapsed(TimeUnit desiredUnit) 

Source Link

Document

Returns the current elapsed time shown on this stopwatch, expressed in the desired time unit, with any fraction rounded down.

Usage

From source file:com.vmware.photon.controller.apife.backends.ResourceTicketSqlBackend.java

/**
 * This method returns the quota consumed via consumeQuota.
 * <p/>//w  ww .j av a2 s  . c  o m
 *
 * @param resourceTicketId - id of the resource ticket
 * @param cost             - the cost object representing how much will be consumed
 */
@Override
@Transactional
public void returnQuota(String resourceTicketId, QuotaCost cost) {
    // return the cost usage. this undoes the
    // quota consumption that occurs during consumeQuota

    Stopwatch resourceTicketWatch = Stopwatch.createStarted();
    ResourceTicketEntity resourceTicket = resourceTicketDao.loadWithUpgradeLock(resourceTicketId);
    resourceTicketWatch.stop();
    logger.info("returnQuota for resourceTicket {}, lock obtained in {} milliseconds", resourceTicket.getId(),
            resourceTicketWatch.elapsed(TimeUnit.MILLISECONDS));

    for (String key : cost.getCostKeys()) {
        resourceTicket.getUsageMap().put(key,
                resourceTicket.getUsageMap().get(key).subtract(cost.getCost(key)));
    }
}

From source file:qa.qcri.nadeef.core.pipeline.CleanExecutor.java

/**
 * Runs the violation detection.// w w  w . j av a 2s .c o  m
 */
public CleanExecutor detect() {
    Stopwatch sw = Stopwatch.createStarted();

    // queryFlow.reset();
    detectFlow.reset();

    // queryFlow.start();
    detectFlow.start();

    // queryFlow.waitUntilFinish();
    detectFlow.waitUntilFinish();

    // clear the new tuples after every run.
    context.clearNewTuples();

    PerfReport.appendMetric(PerfReport.Metric.DetectTime, sw.elapsed(TimeUnit.MILLISECONDS));

    // TODO: remove it.
    System.gc();
    return this;
}

From source file:com.vmware.photon.controller.rootscheduler.service.FlatSchedulerService.java

@Override
public PlaceResponse place(PlaceRequest request) throws TException {
    initRequestId(request);// w w w.ja  v  a 2 s  .  co m
    logger.info("Place request: {}", request);
    Stopwatch watch = Stopwatch.createStarted();

    int numSamples = config.getRootPlaceParams().getMaxFanoutCount();
    long timeoutMs = config.getRootPlaceParams().getTimeout();

    // Pick candidates that satisfy the resource constraints.
    Stopwatch getCandidatesStopwatch = Stopwatch.createStarted();
    List<ResourceConstraint> constraints = getResourceConstraints(request);
    Map<String, ServerAddress> candidates = checker.getCandidates(constraints, numSamples);
    logger.info("elapsed-time flat-place-get-candidates {} milliseconds",
            getCandidatesStopwatch.elapsed(TimeUnit.MILLISECONDS));

    if (candidates.isEmpty()) {
        logger.warn("Place failure, constraints cannot be satisfied for request: {}", request);
        return new PlaceResponse(PlaceResultCode.NO_SUCH_RESOURCE);
    }

    // Send place request to the candidates.
    logger.info("Sending place requests to {} with timeout {} ms", candidates, timeoutMs);
    Stopwatch scoreCandidatesStopwatch = Stopwatch.createStarted();
    final Set<PlaceResponse> okResponses = Sets.newConcurrentHashSet();
    final Set<PlaceResultCode> returnCodes = Sets.newConcurrentHashSet();
    final CountDownLatch done = new CountDownLatch(candidates.size());
    for (Map.Entry<String, ServerAddress> entry : candidates.entrySet()) {
        ServerAddress address = entry.getValue();
        try {
            HostClient hostClient = getHostClient();
            hostClient.setIpAndPort(address.getHost(), address.getPort());
            hostClient.place(request.getResource(), new AsyncMethodCallback<Host.AsyncClient.place_call>() {
                @Override
                public void onComplete(Host.AsyncClient.place_call call) {
                    initRequestId(request);
                    PlaceResponse response;
                    try {
                        response = call.getResult();
                    } catch (TException ex) {
                        onError(ex);
                        return;
                    }
                    logger.info("Received a place response from {}: {}", entry, response);
                    returnCodes.add(response.getResult());
                    if (response.getResult() == PlaceResultCode.OK) {
                        okResponses.add(response);
                    }
                    done.countDown();
                }

                @Override
                public void onError(Exception ex) {
                    initRequestId(request);
                    logger.warn("Failed to get a placement response from {}: {}", entry, ex);
                    done.countDown();
                }
            });
        } catch (RpcException ex) {
            logger.warn("Failed to get a placement response from {}: {}", entry, ex);
            done.countDown();
        }
    }

    // Wait for responses to come back.
    try {
        done.await(timeoutMs, TimeUnit.MILLISECONDS);
    } catch (InterruptedException ex) {
        logger.debug("Got interrupted waiting for place responses", ex);
    }
    logger.info("elapsed-time flat-place-score-candidates {} milliseconds",
            scoreCandidatesStopwatch.elapsed(TimeUnit.MILLISECONDS));

    // Return the best response.
    PlaceResponse response = scoreCalculator.pickBestResponse(okResponses);
    watch.stop();
    if (response == null) {
        // TODO(mmutsuzaki) Arbitrarily defining a precedence for return codes doesn't make sense.
        if (returnCodes.contains(PlaceResultCode.NOT_ENOUGH_CPU_RESOURCE)) {
            response = new PlaceResponse(PlaceResultCode.NOT_ENOUGH_CPU_RESOURCE);
        } else if (returnCodes.contains(PlaceResultCode.NOT_ENOUGH_MEMORY_RESOURCE)) {
            response = new PlaceResponse(PlaceResultCode.NOT_ENOUGH_MEMORY_RESOURCE);
        } else if (returnCodes.contains((PlaceResultCode.NOT_ENOUGH_DATASTORE_CAPACITY))) {
            response = new PlaceResponse(PlaceResultCode.NOT_ENOUGH_DATASTORE_CAPACITY);
        } else if (returnCodes.contains(PlaceResultCode.NO_SUCH_RESOURCE)) {
            response = new PlaceResponse(PlaceResultCode.NO_SUCH_RESOURCE);
        } else if (returnCodes.contains(PlaceResultCode.INVALID_SCHEDULER)) {
            response = new PlaceResponse(PlaceResultCode.INVALID_SCHEDULER);
        } else {
            response = new PlaceResponse(PlaceResultCode.SYSTEM_ERROR);
            String msg = String.format("Received no response in %d ms", watch.elapsed(TimeUnit.MILLISECONDS));
            response.setError(msg);
            logger.error(msg);
        }
    } else {
        logger.info("Returning bestResponse: {} in {} ms", response, watch.elapsed(TimeUnit.MILLISECONDS));
    }
    return response;
}

From source file:org.eclipse.viatra.modelobfuscator.application.common.ModelObfuscatorHeadless.java

/**
 * @param inputs//  w w  w . jav  a  2s.co m
 * @param extensionToFactoryMap
 * @return
 */
private ResourceSetImpl loadInputModels(Map<String, URI> inputs, Map<String, Object> extensionToFactoryMap) {
    ResourceSetImpl resourceSet = new ResourceSetImpl();
    for (Entry<String, URI> inputEntry : inputs.entrySet()) {
        URI uri = inputEntry.getValue();
        // XXX we only support XMI resources in this way
        if (!extensionToFactoryMap.containsKey(uri.fileExtension())) {
            extensionToFactoryMap.put(uri.fileExtension(), new EcoreResourceFactoryImpl());
        }
        System.out.println("Loading resource: " + inputEntry.getKey());
        Stopwatch stopwatch = Stopwatch.createStarted();
        resourceSet.getResource(uri, true);
        stopwatch.stop();
        String elapsedTime = stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms ("
                + stopwatch.elapsed(TimeUnit.NANOSECONDS) + " ns)";
        System.out.println("Loaded resource: " + inputEntry.getKey() + " in " + elapsedTime);
    }
    return resourceSet;
}

From source file:org.eclipse.viatra.modelobfuscator.application.common.ModelObfuscatorHeadless.java

/**
 * @param outputDirectory// w w w .j av a2  s  . c o  m
 * @param inputs
 * @param resourceSet
 */
private void saveObfuscatedModels(File outputDirectory, Map<String, URI> inputs, ResourceSetImpl resourceSet) {
    URI outputDirUri = URI.createFileURI(outputDirectory.getPath());
    for (Entry<String, URI> entry : inputs.entrySet()) {
        URI uri = entry.getValue();
        String fileSegment = uri.lastSegment();
        URI outputUri = outputDirUri.appendSegment(fileSegment);
        Resource resource = resourceSet.getResource(uri, false);
        resource.setURI(outputUri);
        try {
            System.out.println("Saving resource: " + fileSegment);
            Stopwatch stopwatch2 = Stopwatch.createStarted();
            resource.save(null);
            stopwatch2.stop();
            String elapsedTime2 = stopwatch2.elapsed(TimeUnit.MILLISECONDS) + " ms ("
                    + stopwatch2.elapsed(TimeUnit.NANOSECONDS) + " ns)";
            System.out.println("Saved resource: " + fileSegment + " in " + elapsedTime2);
        } catch (IOException e) {
            reportError("Could not save output " + fileSegment);
        }
    }
}

From source file:com.cloudera.director.aws.ec2.ebs.EBSAllocator.java

/**
 * Wait for the specified list of volumes to be attached within a timeout.
 *
 * @param volumeIds collection of volume ids to wait for
 * @return collection of volumes that were successfully attached
 * @throws InterruptedException if the operation is interrupted
 *///from   w w  w  .j ava2  s  . c  om
private Collection<String> waitUntilVolumesAttached(Collection<String> volumeIds) throws InterruptedException {
    checkNotNull(volumeIds);
    if (volumeIds.isEmpty()) {
        LOG.info("No volumes are being attached, skipping wait");
        return Collections.emptySet();
    }

    Set<String> unattachedVolumes = Sets.newHashSet(volumeIds);
    Set<String> attachedVolumes = Sets.newHashSet();

    LOG.info("Waiting for a maximum of {} seconds for volumes to be attached", attachTimeoutSeconds);

    Stopwatch watch = Stopwatch.createStarted();
    while (watch.elapsed(TimeUnit.SECONDS) < attachTimeoutSeconds) {
        DescribeVolumesRequest volumeRequest = new DescribeVolumesRequest().withVolumeIds(unattachedVolumes);
        List<Volume> volumes = client.describeVolumes(volumeRequest).getVolumes();

        for (Volume volume : volumes) {
            VolumeAttachment attachment = Iterables.getOnlyElement(volume.getAttachments());
            VolumeAttachmentState state = VolumeAttachmentState.fromValue(attachment.getState());

            if (state == VolumeAttachmentState.Attached) {
                unattachedVolumes.remove(volume.getVolumeId());
                attachedVolumes.add(volume.getVolumeId());
            }
        }

        if (unattachedVolumes.isEmpty()) {
            return attachedVolumes;
        }

        LOG.info("Waiting on {} out of {} volumes to be attached, next check in {} seconds",
                unattachedVolumes.size(), volumeIds.size(), WAIT_UNTIL_ATTACHED_INTERVAL_SECONDS);
        TimeUnit.SECONDS.sleep(WAIT_UNTIL_ATTACHED_INTERVAL_SECONDS);
    }

    LOG.error("Timed out while waiting for all volumes to be attached, {} out of {} volumes were attached",
            attachedVolumes.size(), volumeIds.size());
    return attachedVolumes;
}

From source file:org.apache.kudu.client.MiniKuduCluster.java

/**
 * Wait up to this instance's "default timeout" for an expected count of TS to
 * connect to the master./*from w  ww . ja v  a 2  s . c o  m*/
 * @param expected How many TS are expected
 * @return true if there are at least as many TS as expected, otherwise false
 */
public boolean waitForTabletServers(int expected) throws Exception {
    int count = 0;
    Stopwatch stopwatch = Stopwatch.createStarted();
    while (count < expected && stopwatch.elapsed(TimeUnit.MILLISECONDS) < defaultTimeoutMs) {
        Thread.sleep(200);
        count = syncClient.listTabletServers().getTabletServersCount();
    }
    return count >= expected;
}

From source file:ch.ge.ve.protopoc.service.protocol.DefaultVotingClient.java

@Override
public List<String> sumbitVote(String identificationCredentials, List<Integer> selections)
        throws VoteCastingException {
    Preconditions.checkState(publicParameters != null,
            "The public parameters need to have been retrieved first");
    Preconditions.checkState(electionSet != null, "The electionSet needs to have been retrieved first");

    Stopwatch stopwatch = Stopwatch.createStarted();
    List<EncryptionPublicKey> publicKeyParts = bulletinBoardService.getPublicKeyParts();
    EncryptionPublicKey systemPublicKey = keyEstablishmentAlgorithms.getPublicKey(publicKeyParts);

    BallotQueryAndRand ballotQueryAndRand = computeBallot(identificationCredentials, selections,
            systemPublicKey);/*from   w  ww  .ja v  a  2s. co m*/
    randomizations = ballotQueryAndRand.getBold_r();
    stopwatch.stop();
    stats.voteEncodingTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);

    List<ObliviousTransferResponse> obliviousTransferResponses = sentBallotAndQuery(
            ballotQueryAndRand.getAlpha());

    stopwatch.reset().start();
    pointMatrix = computePointMatrix(selections, obliviousTransferResponses);
    List<String> returnCodes = voteCastingClientAlgorithms.getReturnCodes(selections, pointMatrix);
    stopwatch.stop();
    stats.verificationCodesComputationTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);

    return returnCodes;
}

From source file:org.glowroot.central.DownstreamServiceImpl.java

boolean isAvailable(String agentId) throws Exception {
    // retry up to 5 seconds on shutting-down response to give agent time to reconnect to
    // another cluster node
    Stopwatch stopwatch = Stopwatch.createStarted();
    while (stopwatch.elapsed(SECONDS) < 5) {
        java.util.Optional<AgentResult> optional = connectedAgents.execute(agentId, 30,
                new IsAvailableFunction());
        if (!optional.isPresent()) {
            return false;
        }/*from   ww w . ja v  a 2s .  com*/
        AgentResult result = optional.get();
        if (!result.shuttingDown()) {
            return true;
        }
        MILLISECONDS.sleep(100);
    }
    // received shutting-down response for 5+ seconds
    return false;
}

From source file:com.google.api.ads.adwords.jaxws.extensions.processors.onfile.ReportProcessorOnFile.java

/**
 * Process the local files delegating the call to the concrete implementation.
 *
 * @param reportType the report type.//  w  w w . ja  va 2s. co m
 * @param localFiles the local files.
 * @param dateStart the start date.
 * @param dateEnd the end date.
 * @param dateRangeType the date range type.
 */
private <R extends Report> void processLocalFiles(String userId, String mccAccountId,
        ReportDefinitionReportType reportType, Collection<File> localFiles, String dateStart, String dateEnd,
        ReportDefinitionDateRangeType dateRangeType) {

    Stopwatch stopwatch = Stopwatch.createStarted();

    @SuppressWarnings("unchecked")
    Class<R> reportBeanClass = (Class<R>) this.csvReportEntitiesMapping.getReportBeanClass(reportType);
    this.processFiles(userId, mccAccountId, reportBeanClass, localFiles, dateRangeType, dateStart, dateEnd);

    stopwatch.stop();
    LOGGER.info(
            "\n* DB Process finished in " + (stopwatch.elapsed(TimeUnit.MILLISECONDS) / 1000) + " seconds ***");
}