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

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

Introduction

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

Prototype

@CheckReturnValue
public static Stopwatch createStarted() 

Source Link

Document

Creates (and starts) a new stopwatch using System#nanoTime as its time source.

Usage

From source file:org.apache.pulsar.functions.worker.SchedulerManager.java

private static Producer<byte[]> createProducer(PulsarClient client, WorkerConfig config) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    for (int i = 0; i < 6; i++) {
        try {/*from  w ww.jav  a2s  . c o  m*/
            return client.newProducer().topic(config.getFunctionAssignmentTopic()).enableBatching(false)
                    .blockIfQueueFull(true).compressionType(CompressionType.LZ4)
                    .sendTimeout(0, TimeUnit.MILLISECONDS).createAsync().get(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            log.error("Interrupted at creating producer to topic {}", config.getFunctionAssignmentTopic(), e);
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            log.error("Encountered exceptions at creating producer for topic {}",
                    config.getFunctionAssignmentTopic(), e);
            throw new RuntimeException(e);
        } catch (TimeoutException e) {
            try {
                log.info(
                        "Can't create a producer on assignment topic {} in {} seconds, retry in 10 seconds ...",
                        stopwatch.elapsed(TimeUnit.SECONDS));
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e1) {
                log.error("Interrupted at creating producer to topic {}", config.getFunctionAssignmentTopic(),
                        e);
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }
            continue;
        }
    }
    throw new RuntimeException(
            "Can't create a producer on assignment topic " + config.getFunctionAssignmentTopic() + " in "
                    + stopwatch.elapsed(TimeUnit.SECONDS) + " seconds, fail fast ...");
}

From source file:cc.kave.commons.pointsto.evaluation.PointsToEvaluation.java

private static void generateUsages(List<PointsToAnalysisFactory> factories) {
    try {/*from  w  ww.  j  a v  a2  s. co  m*/
        Function<PointsToAnalysisFactory, UsageStore> usageStoreFactory = (PointsToAnalysisFactory factory) -> {
            try {
                return new ProjectUsageStore(USAGE_DEST.resolve(factory.getName()));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        };

        DescentStrategy descentStrategy = new SimpleDescentStrategy();
        PointsToUsageGenerator generator = new PointsToUsageGenerator(factories, SRC_PATH, null,
                usageStoreFactory, new TypeStatisticsCollector(new PointsToUsageFilter()), descentStrategy);

        Stopwatch stopwatch = Stopwatch.createStarted();
        generator.generateUsages();
        stopwatch.stop();
        LOGGER.info("Usage generation took {}", stopwatch.toString());

        outputStatisticsCollectors(generator.getStatisticsCollectors());

    } catch (IOException e) {
        LOGGER.error("Error during usage generation", e);
    }
}

From source file:org.eclipse.viatra.dse.evolutionary.EvolutionaryStrategyLogAdapter.java

@Override
public void iterationCompleted(List<TrajectoryFitness> currentPopulation,
        List<? extends List<TrajectoryFitness>> frontsOfCurrentPopulation,
        List<TrajectoryFitness> survivedPopulation, boolean stop) {

    stopwatch.stop();/*  ww w .ja  va2s .c  o  m*/
    long elapsedTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);

    for (TrajectoryFitness trajectoryFitness : survivedPopulation) {

        row.add(DseCsvConstants.configId, configId);
        row.add(DseCsvConstants.runId, runId);
        row.add(DseCsvConstants.iteration, iteration);
        row.add(DseCsvConstants.runTime, elapsedTime);
        row.add(DseCsvConstants.length, trajectoryFitness.trajectory.length);

        row.add(DseCsvConstants.trajectory, "\"" + Arrays.toString(trajectoryFitness.trajectory) + "\"");

        row.add(DseCsvConstants.rank, trajectoryFitness.rank);
        row.add(DseCsvConstants.survive, trajectoryFitness.survive);

        row.add(DseCsvConstants.valid, trajectoryFitness.fitness.isSatisifiesHardObjectives());
        for (IObjective objective : context.getObjectives()) {
            row.add(objective.getName(), trajectoryFitness.fitness.get(objective.getName()));
        }

        csv.appendRow(row);
    }

    iteration++;

    stopwatch = Stopwatch.createStarted();

}

From source file:org.apache.samza.util.EmbeddedTaggedRateLimiter.java

@Override
public Map<String, Integer> acquire(Map<String, Integer> tagToCreditsMap, long timeout, TimeUnit unit) {
    ensureTagsAreValid(tagToCreditsMap);

    long timeoutInNanos = NANOSECONDS.convert(timeout, unit);

    Stopwatch stopwatch = Stopwatch.createStarted();
    return tagToCreditsMap.entrySet().stream().map(e -> {
        String tag = e.getKey();/*from   w ww  .j a  v  a2s.com*/
        int requiredCredits = e.getValue();
        long remainingTimeoutInNanos = Math.max(0L, timeoutInNanos - stopwatch.elapsed(NANOSECONDS));
        com.google.common.util.concurrent.RateLimiter rateLimiter = tagToRateLimiterMap.get(tag);
        int availableCredits = rateLimiter.tryAcquire(requiredCredits, remainingTimeoutInNanos, NANOSECONDS)
                ? requiredCredits
                : 0;
        return new ImmutablePair<>(tag, availableCredits);
    }).collect(Collectors.toMap(ImmutablePair::getKey, ImmutablePair::getValue));
}

From source file:org.apache.cassandra.tracing.TraceState.java

public TraceState(InetAddress coordinator, UUID sessionId, Tracing.TraceType traceType) {
    assert coordinator != null;
    assert sessionId != null;

    this.coordinator = coordinator;
    this.sessionId = sessionId;
    sessionIdBytes = ByteBufferUtil.bytes(sessionId);
    this.traceType = traceType;
    this.ttl = traceType.getTTL();
    watch = Stopwatch.createStarted();
    this.status = Status.IDLE;
}

From source file:com.github.benmanes.caffeine.cache.simulator.Simulator.java

public Simulator() {
    Config config = getContext().system().settings().config().getConfig("caffeine.simulator");
    settings = new BasicSettings(config);

    List<Routee> routes = makeRoutes();
    router = new Router(new BroadcastRoutingLogic(), routes);
    remaining = routes.size();//from  w  w w  .ja  v a2 s .co m

    batchSize = settings.batchSize();
    stopwatch = Stopwatch.createStarted();
    report = settings.report().format().create(config);
    getSelf().tell(Message.START, ActorRef.noSender());
}

From source file:blue.lapis.pore.event.PoreEventRegistry.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static void register() throws IOException {
    Stopwatch watch = Stopwatch.createStarted();

    InputStream in = PoreEventRegistry.class.getResourceAsStream("events.txt");
    if (in == null) {
        Pore.getLogger().warn("No registered events found, Bukkit events will not be called.");
        return;// w w  w. ja  va  2 s  . co m
    }

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            if (line.isEmpty() || line.charAt(0) == '#') {
                continue;
            }

            String owner = line;
            String method = null;

            int pos = line.lastIndexOf(':');
            if (pos >= 0) {
                owner = line.substring(0, pos);
                method = line.substring(pos + 1);
            }

            try {
                // Pff
                Class poreEvent = Class.forName(owner);

                if (method != null) {
                    poreEvent.getMethod(method).invoke(null);
                } else {
                    register(poreEvent, null);
                }
            } catch (Exception e) {
                Pore.getLogger().warn("Failed to register class {} as an event", line, e);
            }
        }
    }

    Pore.getLogger().debug("Registered events in {}", watch.stop());
}

From source file:com.davidbracewell.ml.sequence.hmm.MLFirstOrderHMMLearner.java

@Override
protected void trainAllInstances(List<List<Instance>> instances) {
    log.info("Beginning training [{0} examples] ...", instances.size());
    Stopwatch sw = Stopwatch.createStarted();
    for (Iterator<List<Instance>> iterator = instances.iterator(); iterator.hasNext();) {
        trainOneSequence(iterator.next());
        iterator.remove();/*from  www  .ja  v  a  2 s. c om*/
    }
    sw.stop();
    log.info("Finished training in {0}", sw);
}

From source file:uk.ac.ebi.atlas.search.diffanalytics.DiffAnalyticsDao.java

public List<DiffAnalytics> fetchTopExpressions(Optional<Collection<IndexedAssayGroup>> indexedContrasts,
        Optional<? extends Collection<String>> geneIds, String species) {
    Optional<ImmutableSet<IndexedAssayGroup>> uniqueIndexedContrasts = uniqueIndexedContrasts(indexedContrasts);

    log("fetchTopExpressions", uniqueIndexedContrasts, geneIds);

    Stopwatch stopwatch = Stopwatch.createStarted();

    DatabaseQuery<Object> indexedContrastQuery = buildSelect(uniqueIndexedContrasts, geneIds, species);

    jdbcTemplate.setMaxRows(RESULT_SIZE);

    List<DiffAnalytics> results;

    try {/*from   w  w w.  j a  v  a2  s . c o m*/
        results = jdbcTemplate.query(indexedContrastQuery.getQuery(), dbeRowMapper,
                indexedContrastQuery.getParameters().toArray());

        stopwatch.stop();

        LOGGER.debug(String.format("fetchTopExpressions returned %s expressions in %.2f seconds",
                results.size(), stopwatch.elapsed(TimeUnit.MILLISECONDS) / 1000D));

    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw e;
    }

    return results;

}

From source file:io.ecarf.core.cloud.task.processor.ProcessLoadTask.java

@Override
public void run() throws IOException {

    log.info("START: processing files, memory usage: " + Utils.getMemoryUsageInGB() + "GB" + ", timer: 0s");
    Stopwatch stopwatch = Stopwatch.createStarted();

    EcarfGoogleCloudService cloudService = (EcarfGoogleCloudService) this.getCloudService();

    log.info("Downloading schema terms file: " + schemaTermsFile);

    this.schemaTerms = cloudService.getSetFromCloudStorageFile(schemaTermsFile, bucket);

    String localDictionaryFile = null;

    if (Boolean.valueOf(encode) && StringUtils.isNotBlank(this.dictionaryFile)) {

        log.info("Downloading and loading dictionary into memory from file: " + this.dictionaryFile);

        // 1- Download the dictionary
        localDictionaryFile = Utils.TEMP_FOLDER + dictionaryFile;

        if (FilenameUtils.fileExists(localDictionaryFile)) {
            log.info("Re-using local file: " + localDictionaryFile);

        } else {/* w w w.  j  a v a  2s .c  om*/
            this.cloudService.downloadObjectFromCloudStorage(dictionaryFile, localDictionaryFile, this.bucket);
        }

        log.info("Loading the dictionary from file: " + localDictionaryFile + ", memory usage: "
                + Utils.getMemoryUsageInGB() + "GB, timer: " + stopwatch);

        // 2- Load the dictionary
        try {

            dictionary = Utils.objectFromFile(localDictionaryFile, TermDictionaryCore.class, true, false);

        } catch (ClassNotFoundException e) {

            log.error("Failed to load the dictionary", e);
            throw new IOException(e);
        }

        log.info("Dictionary loaded successfully, memory usage: " + Utils.getMemoryUsageInGB() + "GB, timer: "
                + stopwatch);
    }

    super.run();

    // write term stats to file and upload
    if (!count.isEmpty()) {

        log.info("Saving terms stats");
        String countStatsFile = Utils.TEMP_FOLDER + cloudService.getInstanceId() + Constants.DOT_JSON;
        FileUtils.objectToJsonFile(countStatsFile, count);

        cloudService.uploadFileToCloudStorage(countStatsFile, bucket);
    }

    // delete the dictionary file, free up some space
    if (localDictionaryFile != null) {
        FileUtils.deleteFile(localDictionaryFile);
        // garbage collection
        this.dictionary = null;
    }

    log.info("FINISH: All files are processed and uploaded successfully,, memory usage: "
            + Utils.getMemoryUsageInGB() + "GB, timer: " + stopwatch);
}