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

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

Introduction

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

Prototype

Stopwatch() 

Source Link

Usage

From source file:org.geoserver.web.GeoServerHomePage.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public GeoServerHomePage() {
    GeoServer gs = getGeoServer();/*from ww  w .j ava2 s.c om*/
    ContactInfo contact = gs.getGlobal().getSettings().getContact();

    //add some contact info
    add(new ExternalLink("contactURL", contact.getOnlineResource())
            .add(new Label("contactName", contact.getContactOrganization())));
    {
        String version = String.valueOf(new ResourceModel("version").getObject());
        String contactEmail = contact.getContactEmail();
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("version", version);
        params.put("contactEmail", contactEmail);
        Label label = new Label("footerMessage",
                new StringResourceModel("GeoServerHomePage.footer", this, new Model(params)));
        label.setEscapeModelStrings(false);
        add(label);
    }

    Authentication auth = getSession().getAuthentication();
    if (isAdmin(auth)) {
        Stopwatch sw = new Stopwatch();
        sw.start();
        Fragment f = new Fragment("catalogLinks", "catalogLinksFragment", this);
        Catalog catalog = getCatalog();

        NumberFormat numberFormat = NumberFormat.getIntegerInstance(getLocale());
        numberFormat.setGroupingUsed(true);

        final Filter allLayers = acceptAll();
        final Filter allStores = acceptAll();
        final Filter allWorkspaces = acceptAll();

        final int layerCount = catalog.count(LayerInfo.class, allLayers);
        final int storesCount = catalog.count(StoreInfo.class, allStores);
        final int wsCount = catalog.count(WorkspaceInfo.class, allWorkspaces);

        f.add(new BookmarkablePageLink("layersLink", LayerPage.class)
                .add(new Label("nlayers", numberFormat.format(layerCount))));
        f.add(new BookmarkablePageLink("addLayerLink", NewLayerPage.class));

        f.add(new BookmarkablePageLink("storesLink", StorePage.class)
                .add(new Label("nstores", numberFormat.format(storesCount))));
        f.add(new BookmarkablePageLink("addStoreLink", NewDataPage.class));

        f.add(new BookmarkablePageLink("workspacesLink", WorkspacePage.class)
                .add(new Label("nworkspaces", numberFormat.format(wsCount))));
        f.add(new BookmarkablePageLink("addWorkspaceLink", WorkspaceNewPage.class));
        add(f);

        sw.stop();
    } else {
        Label placeHolder = new Label("catalogLinks");
        placeHolder.setVisible(false);
        add(placeHolder);
    }

    final IModel<List<GeoServerHomePageContentProvider>> contentProviders;
    contentProviders = getContentProviders(GeoServerHomePageContentProvider.class);
    ListView<GeoServerHomePageContentProvider> contentView = new ListView<GeoServerHomePageContentProvider>(
            "contributedContent", contentProviders) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(ListItem<GeoServerHomePageContentProvider> item) {
            GeoServerHomePageContentProvider provider = item.getModelObject();
            Component extraContent = provider.getPageBodyComponent("contentList");
            if (null == extraContent) {
                Label placeHolder = new Label("contentList");
                placeHolder.setVisible(false);
                extraContent = placeHolder;
            }
            item.add(extraContent);
        }
    };
    add(contentView);

    final IModel<List<CapabilitiesHomePageLinkProvider>> capsProviders;
    capsProviders = getContentProviders(CapabilitiesHomePageLinkProvider.class);

    ListView<CapabilitiesHomePageLinkProvider> capsView = new ListView<CapabilitiesHomePageLinkProvider>(
            "providedCaps", capsProviders) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(ListItem<CapabilitiesHomePageLinkProvider> item) {
            CapabilitiesHomePageLinkProvider provider = item.getModelObject();
            Component capsList = provider.getCapabilitiesComponent("capsList");
            item.add(capsList);
        }
    };
    add(capsView);
}

From source file:processing.FolkRankCalculator.java

private static void startFolkRankCreation(BookmarkReader reader, int sampleSize) {
    timeString = "";
    System.out.println("\nStart FolkRank Calculation for Tags");
    frResults = new ArrayList<int[]>();
    prResults = new ArrayList<int[]>();
    int size = reader.getUserLines().size();
    int trainSize = size - sampleSize;
    Stopwatch timer = new Stopwatch();
    timer.start();/*from w w w .  j a  v a 2s .  c o m*/
    FactReader factReader = new WikipediaFactReader(reader, trainSize, 3);
    FactPreprocessor prep = new FactReaderFactPreprocessor(factReader);
    prep.process();
    FolkRankData facts = prep.getFolkRankData();

    FolkRankParam param = new FolkRankParam();
    FolkRankPref pref = new FolkRankPref(new double[] { 1.0, 1.0, 1.0 });
    int usrCounts = facts.getCounts()[1].length;
    System.out.println("Users: " + usrCounts);
    int resCounts = facts.getCounts()[2].length;
    System.out.println("Resources: " + resCounts);
    double[][] prefWeights = new double[][] { new double[] {}, new double[] { usrCounts },
            new double[] { resCounts } };
    FolkRankAlgorithm folk = new FolkRankAlgorithm(param);
    timer.stop();
    long trainingTime = timer.elapsed(TimeUnit.MILLISECONDS);

    timer = new Stopwatch();
    // start FolkRank        
    for (int i = trainSize; i < size; i++) {
        timer.start();
        UserData data = reader.getUserLines().get(i);
        int u = data.getUserID();
        int[] uPrefs = (u < usrCounts ? new int[] { u } : new int[] {});
        int r = data.getWikiID();
        int[] rPrefs = (r < resCounts ? new int[] { r } : new int[] {});
        pref.setPreference(new int[][] { new int[] {}, uPrefs, rPrefs }, prefWeights);
        FolkRankResult result = folk.computeFolkRank(facts, pref);

        int[] topTags = new int[10];
        SortedSet<ItemWithWeight> topKTags = ItemWithWeight.getTopK(facts, result.getWeights(), 10, 0);
        int count = 0;
        for (ItemWithWeight item : topKTags) {
            topTags[count++] = item.getItem();
        }
        frResults.add(topTags);
        timer.stop();

        int[] topTagsPr = new int[10];
        SortedSet<ItemWithWeight> topKTagsPr = ItemWithWeight.getTopK(facts, result.getAPRWeights(), 10, 0);
        count = 0;
        for (ItemWithWeight item : topKTagsPr) {
            topTagsPr[count++] = item.getItem();
        }
        prResults.add(topTagsPr);
        //System.out.println(u + "|" + data.getTags().toString().replace("[", "").replace("]", "") + 
        //                  "|" + Arrays.toString(topTags).replace("[", "").replace("]", "") + 
        //                  "|" + Arrays.toString(topTagsPr).replace("[", "").replace("]", ""));
    }
    long testTime = timer.elapsed(TimeUnit.MILLISECONDS);
    timeString += ("Full training time: " + trainingTime + "\n");
    timeString += ("Full test time: " + testTime + "\n");
    timeString += ("Average test time: " + testTime / (double) sampleSize) + "\n";
    timeString += ("Total time: " + (trainingTime + testTime) + "\n");
}

From source file:org.icgc.dcc.submission.validation.key.core.KVValidatorRunner.java

@SuppressWarnings("deprecation")
private static Stopwatch createStopwatch() {
    // Can't use the new API here because Hadoop doesn't know about it cluster side. Trying to use it will result in
    // errors./*from   w ww  . j a  va  2s. c  o  m*/
    return new Stopwatch().start();
}

From source file:com.couchbase.roadrunner.workloads.GetsCasWorkload.java

private long getsWorkloadWithMeasurement(String key) {
    Stopwatch watch = new Stopwatch().start();
    long cas = getsWorkload(key);
    watch.stop();//  w  w  w  .  j a v a2  s .c o m
    addMeasure("gets", watch);
    return cas;
}

From source file:org.apache.drill.exec.physical.impl.xsort.BatchGroup.java

private VectorContainer getBatch() throws IOException {
    assert fs != null;
    assert path != null;
    if (inputStream == null) {
        inputStream = fs.open(path);//from www. ja va2 s.c  o  m
    }
    VectorAccessibleSerializable vas = new VectorAccessibleSerializable(allocator);
    Stopwatch watch = new Stopwatch();
    watch.start();
    vas.readFromStream(inputStream);
    VectorContainer c = vas.get();
    //    logger.debug("Took {} us to read {} records", watch.elapsed(TimeUnit.MICROSECONDS), c.getRecordCount());
    spilledBatches--;
    currentContainer.zeroVectors();
    Iterator<VectorWrapper<?>> wrapperIterator = c.iterator();
    for (VectorWrapper w : currentContainer) {
        TransferPair pair = wrapperIterator.next().getValueVector().makeTransferPair(w.getValueVector());
        pair.transfer();
    }
    currentContainer.setRecordCount(c.getRecordCount());
    c.zeroVectors();
    return c;
}

From source file:fr.ippon.wip.filter.PerformanceFilter.java

public void doFilter(ResourceRequest request, ResourceResponse response, FilterChain chain)
        throws IOException, PortletException {
    Stopwatch timeProcess = new Stopwatch().start();
    chain.doFilter(request, response);//from w  w  w  . j av a 2 s.c  o m
    StringBuilder data = new StringBuilder();
    writePerformance(data.append("RESOURCE\t").append(request.getParameter(WIPortlet.LINK_URL_KEY) + "\t")
            .append(timeProcess.elapsedMillis() + "\t"));
}

From source file:com.flipkart.foxtrot.core.querystore.impl.ElasticsearchQueryStore.java

@Override
public void save(String table, Document document) throws QueryStoreException {
    table = ElasticsearchUtils.getValidTableName(table);
    try {/*from w w  w  .j a v a  2 s . c  o m*/
        if (!tableMetadataManager.exists(table)) {
            throw new QueryStoreException(QueryStoreException.ErrorCode.NO_SUCH_TABLE,
                    "No table exists with the name: " + table);
        }
        if (new DateTime().plusDays(1).minus(document.getTimestamp()).getMillis() < 0) {
            return;
        }
        dataStore.save(tableMetadataManager.get(table), document);
        long timestamp = document.getTimestamp();
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.start();
        connection.getClient().prepareIndex().setIndex(ElasticsearchUtils.getCurrentIndex(table, timestamp))
                .setType(ElasticsearchUtils.TYPE_NAME).setId(document.getId())
                .setTimestamp(Long.toString(timestamp)).setSource(mapper.writeValueAsBytes(document.getData()))
                .setConsistencyLevel(WriteConsistencyLevel.QUORUM).execute().get(2, TimeUnit.SECONDS);
        logger.info(String.format("ES took : %d table : %s", stopwatch.elapsedMillis(), table));
    } catch (QueryStoreException ex) {
        throw ex;
    } catch (DataStoreException ex) {
        DataStoreException.ErrorCode code = ex.getErrorCode();
        if (code.equals(DataStoreException.ErrorCode.STORE_INVALID_REQUEST)
                || code.equals(DataStoreException.ErrorCode.STORE_INVALID_DOCUMENT)) {
            throw new QueryStoreException(QueryStoreException.ErrorCode.INVALID_REQUEST, ex.getMessage(), ex);
        } else {
            throw new QueryStoreException(QueryStoreException.ErrorCode.DOCUMENT_SAVE_ERROR, ex.getMessage(),
                    ex);
        }
    } catch (JsonProcessingException ex) {
        throw new QueryStoreException(QueryStoreException.ErrorCode.INVALID_REQUEST, ex.getMessage(), ex);
    } catch (Exception ex) {
        throw new QueryStoreException(QueryStoreException.ErrorCode.DOCUMENT_SAVE_ERROR, ex.getMessage(), ex);
    }
}

From source file:com.Grande.GSM.BACCWS_WAR.WS.REST.EOS.BACCAdminEndpoint.java

@Path("/AllowedProperties")
@GET//from  w ww  . j  av  a2 s  . c  o  m
public String fetchAllowedProperties() {

    // <editor-fold defaultstate="collapsed" desc="****** Method vars ******">
    final Stopwatch timer = new Stopwatch();
    final QueryResponse qRes = new QueryResponse();
    String strResponse = null;
    List lstResult = null;
    // start the execution timer
    timer.start();
    // </editor-fold>

    try {

        qRes.vSetNode(java.net.InetAddress.getLocalHost().getHostName());
        lstResult = this.bacEJB.lstFetchAllowedProperties();
        qRes.vSetSuccessFlag(true);
        qRes.vSquashResult(lstResult);

    } catch (Exception e) {

        // <editor-fold defaultstate="collapsed" desc="****** Handle failures ******">
        qRes.vSetSuccessFlag(false);
        // handle NPE differently since getMessage() is null
        if (e instanceof NullPointerException) {
            qRes.vSetMessage("NPE occured when serializing result to JSON! " + "File: "
                    + e.getStackTrace()[0].getFileName() + ", " + "Method: "
                    + e.getStackTrace()[0].getMethodName() + ", " + "Line: "
                    + e.getStackTrace()[0].getLineNumber());
        } else {
            qRes.vSetMessage(e.getMessage());
        }
        SimpleLogging.vLogException(this.strThreadId, e);
        // </editor-fold>

    } finally {

        // <editor-fold defaultstate="collapsed" desc="****** Stop timer, convert response to JSON ******">
        timer.stop();
        qRes.vSetRoundTrip(String.valueOf(timer.elapsedTime(TimeUnit.SECONDS)) + "."
                + String.valueOf(timer.elapsedTime(TimeUnit.MILLISECONDS)));
        strResponse = this.trnBN.strQueryResponseToJSON(qRes);
        SimpleLogging.vLogEvent(this.strThreadId + "|" + qRes.strGetRoundTripInSeconds() + "s",
                "retrieved " + qRes.intGetDataCount() + " records");
        // </editor-fold>

    }
    return strResponse;
}

From source file:pl.llp.aircasting.view.NoisePlot.java

@Override
protected void onDraw(Canvas canvas) {
    Stopwatch stopwatch = new Stopwatch().start();

    bottom = thresholds.getValue(sensor, MeasurementLevel.VERY_LOW);
    top = thresholds.getValue(sensor, MeasurementLevel.VERY_HIGH);

    Paint paint = new Paint();
    drawBackground(canvas, paint);//from  ww w  .j  a v a2 s  . c om

    if (!measurements.isEmpty()) {
        measurements = aggregator.smoothenSamplesToReduceCount(newArrayList(measurements), 1000);
        Path path = new Path();

        float lastY = project(measurements.get(0).getValue());
        path.moveTo(0, lastY);

        // Avoid concurrent modification
        for (int i = 1; i < measurements.size(); i++) {
            Measurement measurement = measurements.get(i);
            Point place = place(measurement);
            path.lineTo(place.x, place.y);
        }
        Logger.logGraphPerformance("onDraw to path creation took " + stopwatch.elapsed(TimeUnit.MILLISECONDS));

        initializePaint(paint);

        canvas.drawPath(path, paint);
        Logger.logGraphPerformance("onDraw to path draw took " + stopwatch.elapsed(TimeUnit.MILLISECONDS));

        for (Note note : notes) {
            drawNote(canvas, note);
        }

        if (settingsHelper.showGraphMetadata()) {
            String message = "[" + measurements.size() + "] pts";
            String message2 = "drawing took " + stopwatch.elapsed(TimeUnit.MILLISECONDS);
            long textSize = getResources().getDimensionPixelSize(R.dimen.debugFontSize);
            Paint textPaint = new Paint();
            textPaint.setColor(Color.WHITE);
            textPaint.setAlpha(OPAQUE);
            textPaint.setAntiAlias(true);
            textPaint.setTextSize(textSize);

            float textWidth = Math.max(textPaint.measureText(message), textPaint.measureText(message2));

            canvas.drawText(message, getWidth() - textWidth - 5, getHeight() - textSize - 5, textPaint);
            canvas.drawText(message2, getWidth() - textWidth - 5, getHeight() - 5, textPaint);
        }
    }
}

From source file:org.apache.drill.exec.physical.impl.TopN.PriorityQueueTemplate.java

@Override
public void add(FragmentContext context, RecordBatchData batch) throws SchemaChangeException {
    Stopwatch watch = new Stopwatch();
    watch.start();/*  w w  w  .  jav a  2 s  . c  o  m*/
    if (hyperBatch == null) {
        hyperBatch = new ExpandableHyperContainer(batch.getContainer());
    } else {
        hyperBatch.addBatch(batch.getContainer());
    }

    doSetup(context, hyperBatch, null); // may not need to do this every time

    int count = 0;
    SelectionVector2 sv2 = null;
    if (hasSv2) {
        sv2 = batch.getSv2();
    }
    for (; queueSize < limit && count < batch.getRecordCount(); count++) {
        heapSv4.set(queueSize, batchCount, hasSv2 ? sv2.getIndex(count) : count);
        queueSize++;
        siftUp();
    }
    for (; count < batch.getRecordCount(); count++) {
        heapSv4.set(limit, batchCount, hasSv2 ? sv2.getIndex(count) : count);
        if (compare(limit, 0) < 0) {
            swap(limit, 0);
            siftDown();
        }
    }
    batchCount++;
    if (hasSv2) {
        sv2.clear();
    }
    logger.debug("Took {} us to add {} records", watch.elapsed(TimeUnit.MICROSECONDS), count);
}