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:it.units.malelab.ege.core.evolver.geneoptimalmixing.GOMEvolver.java

@Override
public List<Node<T>> solve(ExecutorService executor, Random random, List<EvolverListener<G, T, F>> listeners)
        throws InterruptedException, ExecutionException {
    LoadingCache<G, Pair<Node<T>, Map<String, Object>>> mappingCache = CacheBuilder.newBuilder()
            .maximumSize(CACHE_SIZE).recordStats().build(getMappingCacheLoader());
    LoadingCache<Node<T>, F> fitnessCache = CacheBuilder.newBuilder().maximumSize(CACHE_SIZE).recordStats()
            .build(getFitnessCacheLoader());
    Stopwatch stopwatch = Stopwatch.createStarted();
    //initialize population
    int births = 0;
    List<Callable<List<Individual<G, T, F>>>> tasks = new ArrayList<>();
    for (G genotype : configuration.getPopulationInitializer().build(configuration.getPopulationSize(),
            configuration.getInitGenotypeValidator(), random)) {
        tasks.add(individualFromGenotypeCallable(genotype, 0, mappingCache, fitnessCache, listeners, null, null,
                executor));//from   ww  w. j  a v  a2s .  co m
        births = births + 1;
    }
    List<Individual<G, T, F>> population = new ArrayList<>(Utils.getAll(executor.invokeAll(tasks)));
    Utils.broadcast(new EvolutionStartEvent<>(this, cacheStats(mappingCache, fitnessCache)), listeners,
            executor);
    Utils.broadcast(new GenerationEvent<>(configuration.getRanker().rank(population, random),
            (int) Math.floor(actualBirths(births, fitnessCache) / configuration.getPopulationSize()), this,
            cacheStats(mappingCache, fitnessCache)), listeners, executor);
    Set<Individual<G, T, F>> bests = new LinkedHashSet<>();
    //iterate
    while (Math.round(actualBirths(births, fitnessCache) / configuration.getPopulationSize()) < configuration
            .getNumberOfGenerations()) {
        //learn fos
        List<ConstrainedSequence> genotypes = new ArrayList<>(population.size());
        for (Individual<G, T, F> individual : population) {
            genotypes.add(individual.getGenotype());
        }
        Set<Set<Integer>> fos = configuration.getFosBuilder().build(genotypes, random);
        //apply gom
        int lastIterationActualBirths = actualBirths(births, fitnessCache);
        tasks.clear();
        for (Individual<G, T, F> individual : population) {
            tasks.add(gomCallable(population, individual, fos, random,
                    (int) Math.floor(actualBirths(births, fitnessCache) / configuration.getPopulationSize()),
                    configuration.getRanker(), configuration.getMutationOperator(), mappingCache, fitnessCache,
                    population.size() * configuration.getNumberOfGenerations(), listeners, executor,
                    stopwatch));
        }
        List<Individual<G, T, F>> newPopulation = new ArrayList<>();
        for (Future<List<Individual<G, T, F>>> result : executor.invokeAll(tasks)) {
            List<Individual<G, T, F>> newIndividuals = result.get();
            newPopulation.add(newIndividuals.get(0));
            births = births + fos.size();
            if (Math.round(
                    actualBirths(births, fitnessCache) / configuration.getPopulationSize()) >= configuration
                            .getNumberOfGenerations()) {
                break;
            }
        }
        for (int i = 0; i < newPopulation.size(); i++) {
            population.set(i, newPopulation.get(i));
        }
        //update best rank
        List<Individual<G, T, F>> populationWithBests = new ArrayList<>(population);
        populationWithBests.addAll(bests);
        List<List<Individual<G, T, F>>> rankedPopulationWithBests = configuration.getRanker()
                .rank(populationWithBests, random);
        bests.clear();
        for (Individual<G, T, F> individual : rankedPopulationWithBests.get(0)) {
            bests.add(individual);
            if (bests.size() >= configuration.getPopulationSize()) {
                break;
            }
        }
        Utils.broadcast(new GenerationEvent<>(rankedPopulationWithBests,
                (int) Math.floor(actualBirths(births, fitnessCache) / configuration.getPopulationSize()), this,
                cacheStats(mappingCache, fitnessCache)), listeners, executor);
        if (configuration.getMaxRelativeElapsed() > 0) {
            //check if relative elapsed time exceeded
            double avgFitnessComputationNanos = fitnessCache.stats().averageLoadPenalty();
            double elapsedNanos = stopwatch.elapsed(TimeUnit.NANOSECONDS);
            if (elapsedNanos / avgFitnessComputationNanos > configuration.getMaxRelativeElapsed()) {
                break;
            }
        }
        if (configuration.getMaxElapsed() > 0) {
            //check if elapsed time exceeded
            if (stopwatch.elapsed(TimeUnit.SECONDS) > configuration.getMaxElapsed()) {
                break;
            }
        }
        if (configuration.getProblem().getLearningFitnessComputer().bestValue() != null) {
            //check if optimal solution found
            if (rankedPopulationWithBests.get(0).get(0).getFitness()
                    .equals(configuration.getProblem().getLearningFitnessComputer().bestValue())) {
                break;
            }
        }
    }
    //end
    List<Node<T>> bestPhenotypes = new ArrayList<>();
    List<Individual<G, T, F>> populationWithBests = new ArrayList<>(population);
    populationWithBests.addAll(bests);
    List<List<Individual<G, T, F>>> rankedPopulationWithBests = configuration.getRanker()
            .rank(populationWithBests, random);
    Utils.broadcast(new EvolutionEndEvent<>((List) rankedPopulationWithBests,
            (int) Math.floor(births / configuration.getPopulationSize()), this,
            cacheStats(mappingCache, fitnessCache)), listeners, executor);
    for (Individual<G, T, F> individual : rankedPopulationWithBests.get(0)) {
        bestPhenotypes.add(individual.getPhenotype());
    }
    return bestPhenotypes;
}

From source file:com.elite.tools.soar.NetworkDispatcher.java

@Override
public void run() {
    InnerRequest<?> request;/*w  w  w  . j  a va 2s.co  m*/
    while (true) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        // release previous request object to avoid leaking request object when mQueue is drained.
        // ???queue?
        request = null;
        try {
            // ?
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }

        try {
            // ????
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }

            // 
            NetworkResponse networkResponse = mNetwork.performRequest(request);

            // ?304???
            // ?????????
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }

            // ??
            InnerResponse<?> response = request.parseNetworkResponse(networkResponse);

            // 
            // TODO: 304??metadata??
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
            }

            // ??
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (SoarError soarError) {
            //??
            soarError.setNetworkTimeMs(stopwatch.stop().elapsed(TimeUnit.MILLISECONDS));
            parseAndDeliverNetworkError(request, soarError);
        } catch (Exception e) {
            //???SoarError
            LOG.error("Unhandled exception {}", e);
            SoarError soarError = new SoarError(e);
            soarError.setNetworkTimeMs(stopwatch.stop().elapsed(TimeUnit.MILLISECONDS));
            mDelivery.postError(request, soarError);
        } finally {
            if (stopwatch.isRunning()) {
                stopwatch.stop();
            }
        }
    }
}

From source file:com.twitter.distributedlog.io.LZ4CompressionCodec.java

@Override
public byte[] decompress(byte[] data, int offset, int length, OpStatsLogger decompressionStat) {
    Preconditions.checkNotNull(data);/*  w  ww.jav  a 2 s .  c  om*/
    Preconditions.checkArgument(offset >= 0 && offset < data.length);
    Preconditions.checkArgument(length >= 0);
    Preconditions.checkNotNull(decompressionStat);

    Stopwatch watch = Stopwatch.createStarted();
    // Assume that we have a compression ratio of 1/3.
    int outLength = length * 3;
    while (true) {
        try {
            byte[] decompressed = safeDecompressor.decompress(data, offset, length, outLength);
            decompressionStat.registerSuccessfulEvent(watch.elapsed(TimeUnit.MICROSECONDS));
            return decompressed;
        } catch (LZ4Exception e) {
            outLength *= 2;
        }
    }
}

From source file:org.simmetrics.performance.BatchPerformance.java

private static void testCompareUncached() {
    StringMetric metric = new StringMetricBuilder().with(new SimonWhite<String>())
            .tokenize(new WhitespaceTokenizer()).tokenize(new QGramTokenizer(2)).build();

    Stopwatch sw = Stopwatch.createStarted();
    for (int n = 0; n < TEST_REPEATS; n++) {
        @SuppressWarnings("unused")
        final float[] results = compare(metric, name, names);

    }//w  w w .  j  av  a 2s.  com
    sw.stop();

    String message = "Uncached performance %s ms. Repeats %s.";

    System.out.println(String.format(message, sw.elapsed(TimeUnit.MILLISECONDS), TEST_REPEATS));

}

From source file:com.elite.tools.soar.toolbox.BasicNetwork.java

@Override
public NetworkResponse performRequest(InnerRequest<?> request) throws SoarError {
    Stopwatch stopwatch = Stopwatch.createStarted();
    while (true) {
        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = Collections.emptyMap();
        try {// w  ww.ja va  2  s.  co  m
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            addCacheHeaders(headers, request.getCacheEntry());

            httpResponse = mHttpStack.performRequest(request, headers);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();

            responseHeaders = convertHeaders(httpResponse.getAllHeaders());
            // ??
            if (statusCode == HttpStatus.SC_NOT_MODIFIED) {

                Cache.Entry entry = request.getCacheEntry();
                if (entry == null) {
                    return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, null, responseHeaders, true,
                            stopwatch.elapsed(TimeUnit.MILLISECONDS));
                }

                // A HTTP 304 response does not have all header fields. We
                // have to use the header fields from the cache entry plus
                // the new ones from the response.
                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
                entry.responseHeaders.putAll(responseHeaders);
                return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, entry.data, entry.responseHeaders, true,
                        stopwatch.elapsed(TimeUnit.MILLISECONDS));
            }

            // ????
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                    || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                String newUrl = responseHeaders.get("Location");
                request.setRedirectUrl(newUrl);
            }

            // 204??(No Content)???
            if (httpResponse.getEntity() != null) {
                responseContents = entityToBytes(httpResponse.getEntity());
            } else {
                responseContents = new byte[0];
            }

            // ?LOG
            long requestLifetime = stopwatch.elapsed(TimeUnit.MILLISECONDS);
            logSlowRequests(requestLifetime, request, responseContents, statusLine);

            if (statusCode < 200 || statusCode > 299) {
                throw new IOException();
            }
            return new NetworkResponse(statusCode, responseContents, responseHeaders, false,
                    stopwatch.elapsed(TimeUnit.MILLISECONDS));
        } catch (SocketTimeoutException e) {
            attemptRetryOnException("socket", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            attemptRetryOnException("connection", request, new TimeoutError());
        } catch (MalformedURLException e) {
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (IOException e) {
            int statusCode;
            NetworkResponse networkResponse;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusLine().getStatusCode();
            } else {
                throw new NoConnectionError(e);
            }
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                    || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                LOG.error("InnerRequest at {} has been redirected to {}", request.getOriginUrl(),
                        request.getUrl());
            } else {
                LOG.error("Unexpected response code {} for {}", statusCode, request.getUrl());
            }
            if (responseContents != null) {
                networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false,
                        stopwatch.elapsed(TimeUnit.MILLISECONDS));
                if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                        || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                    attemptRetryOnException("redirect", request, new RedirectError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(e);
            }
        }
    }
}

From source file:benchmarkio.consumer.rabbitmq.RabbitMQMessageConsumer.java

@Override
public Histogram call() throws Exception {
    final String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, topic, "#");

    final QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, true, consumer);

    logger.info("topic: {}, queueName: {}", topic, queueName);

    int messageCount = 0;

    // Note that this is a polling consumer and will be terminated
    // whenever the Consts.POLLING_CONSUMER_MAX_IDLE_TIME_MS passes and no new messages have arrived.
    while (true) {
        // Start/*from w ww  . j  av a2 s.c  om*/
        final Stopwatch stopwatch = Stopwatch.createStarted();

        final QueueingConsumer.Delivery delivery = consumer
                .nextDelivery(Consts.POLLING_CONSUMER_MAX_IDLE_TIME_MS);

        if (delivery == null) {
            logger.info("Consumer was terminated through timeout");

            break;
        }

        final byte[] message = delivery.getBody();

        messageCount++;

        final String routingKey = delivery.getEnvelope().getRoutingKey();

        // End
        stopwatch.stop();
        histogram.recordValue(stopwatch.elapsed(Consts.TIME_UNIT_FOR_REPORTING));
    }

    logger.info("In total consumed {} messages", messageCount);

    return histogram;
}

From source file:hu.bme.mit.trainbenchmark.benchmark.util.BenchmarkResult.java

public void restartClock() {
    stopwatch = Stopwatch.createStarted();
}

From source file:com.microsoft.azure.servicebus.samples.prefetch.Prefetch.java

long sendAndReceiveMessages(IMessageSender sender, IMessageReceiver receiver, int messageCount)
        throws Exception {
    // Now we can start sending messages.
    Random rnd = new Random();
    byte[] mockPayload = new byte[100]; // 100 random-byte payload

    rnd.nextBytes(mockPayload);//from   w  ww  . j  a  v a 2s  .co m

    System.out.printf("\nSending %d messages to the queue\n", messageCount);
    ArrayList<CompletableFuture<Void>> sendOps = new ArrayList<>();
    for (int i = 0; i < messageCount; i++) {
        IMessage message = new Message(mockPayload);
        message.setTimeToLive(Duration.ofMinutes(5));
        sendOps.add(sender.sendAsync(message));
    }
    CompletableFuture.allOf(sendOps.toArray(new CompletableFuture<?>[sendOps.size()])).join();

    System.out.printf("Send completed\n");

    // Receive the messages
    System.out.printf("Receiving messages...\n");

    // Start stopwatch
    Stopwatch stopWatch = Stopwatch.createStarted();

    IMessage receivedMessage = receiver.receive(Duration.ofSeconds(5));
    while (receivedMessage != null) {
        // here's where you'd do any work

        // complete (round trips)
        receiver.complete(receivedMessage.getLockToken());

        if (--messageCount <= 0)
            break;

        // now get the next message
        receivedMessage = receiver.receive(Duration.ofSeconds(5));
    }
    // Stop the stopwatch
    stopWatch.stop();

    System.out.printf("Receive completed\n");

    long timeTaken = stopWatch.elapsed(TimeUnit.MILLISECONDS);
    System.out.printf("Time to receive and complete all messages = %d milliseconds\n", timeTaken);

    return timeTaken;
}

From source file:com.edduarte.vokter.keyword.KeywordBuilder.java

public Keyword build(ParserPool parserPool) {
    Stopwatch sw = Stopwatch.createStarted();

    // step 3) Takes a parser from the parser-pool.
    Parser parser;/*  w ww .ja  v a 2  s  . c  o  m*/
    try {
        parser = parserPool.take();
    } catch (InterruptedException ex) {
        logger.error(ex.getMessage(), ex);
        return null;
    }

    KeywordPipeline pipeline = new KeywordPipeline(

            // the language detection model
            langDetector,

            // the textual input of the keyword
            keywordInput,

            // the parser that will be used for query parsing and term
            // detection
            parser,

            // the set of stopwords that will be filtered during tokenization
            isStoppingEnabled,

            // the stemmer class that will be used to stem the detected tokens
            isStemmingEnabled,

            // flag that forces every found token to be
            // lower case, matching, for example, the words
            // 'be' and 'Be' as the same token
            ignoreCase);

    // step 5) Process the document asynchronously.
    Keyword aux;
    try {
        aux = pipeline.call();
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
        return null;
    }
    final Keyword keyword = aux;

    // step 6) Place the parser back in the parser-pool.
    try {
        parserPool.place(parser);
    } catch (InterruptedException ex) {
        logger.error(ex.getMessage(), ex);
        return null;
    }

    logger.info("Completed building keywords '{}' in {}", keywordInput, sw.toString());
    return keyword;
}

From source file:org.terasology.polyworld.elevation.ElevationProvider.java

@Override
public void process(GeneratingRegion region) {
    Border3D border = region.getBorderForFacet(SurfaceHeightFacet.class);
    SurfaceHeightFacet facet = new SurfaceHeightFacet(region.getRegion(), border);

    ElevationModelFacet elevationModelFacet = region.getRegionFacet(ElevationModelFacet.class);
    SeaLevelFacet seaLevelFacet = region.getRegionFacet(SeaLevelFacet.class);
    float seaLevel = seaLevelFacet.getSeaLevel();
    float seaFloor = 2.0f;
    float maxHeight = 50.0f;

    GraphFacet graphFacet = region.getRegionFacet(GraphFacet.class);

    // make sure that the sea is at least 1 block deep
    if (seaLevel <= seaFloor) {
        seaLevel = seaFloor + 1;/*from w ww.j  a  v  a2 s.co m*/
    }

    final boolean traceLog = logger.isTraceEnabled();
    Stopwatch sw = traceLog ? Stopwatch.createStarted() : null;

    Graph graph = null;
    Triangle prevTri = null;
    float wreg = 0;
    float wc1 = 0;
    float wc2 = 0;

    ElevationModel elevation = null;

    for (Vector2i p : facet.getWorldRegion()) {
        if (graph == null || !graph.getBounds().contains(p)) {
            graph = graphFacet.getWorld(p.x, 0, p.y);
            elevation = elevationModelFacet.get(graph);
        }

        Triangle tri = graphFacet.getWorldTriangle(p.x, 0, p.y);

        if (tri != prevTri) {
            wreg = elevation.getElevation(tri.getRegion());
            wc1 = elevation.getElevation(tri.getCorner1());
            wc2 = elevation.getElevation(tri.getCorner2());
            prevTri = tri;
        }

        float ele = tri.computeInterpolated(new Vector2f(p.x, p.y), wreg, wc1, wc2);
        float blockHeight = convertModelElevation(seaLevel, seaFloor, maxHeight, ele);

        facet.setWorld(p, blockHeight);
    }

    if (traceLog) {
        logger.trace("Created elevation facet for {} in {}ms.", facet.getWorldRegion(),
                sw.elapsed(TimeUnit.MILLISECONDS));
    }

    region.setRegionFacet(SurfaceHeightFacet.class, facet);
}