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:com.google.collide.server.shared.util.FileHasher.java

public static ByteString getSha1(String contents) {
    Stopwatch stopWatch = new Stopwatch().start();
    ByteString sha1 = ByteString.copyFrom(Hashing.sha1().hashString(contents).asBytes());
    return sha1;/*from w  ww.jav a2s . c o m*/
}

From source file:com.github.zhongl.util.Benchmarks.java

public static void benchmark(String name, Runnable runnable, int times) {
    Stopwatch stopwatch = new Stopwatch().start();
    runnable.run();//  w ww.  ja  v  a  2 s  .  co m
    stopwatch.stop();

    long latency = stopwatch.elapsedTime(TimeUnit.NANOSECONDS) / times;
    double tps = times * 1.0 / stopwatch.elapsedTime(TimeUnit.MILLISECONDS) * 1000;

    System.out.println(format("{0} : elpase[{1}], latency[{2, number}ns], TPS[{3, number,#.##}]", name,
            stopwatch, latency, tps));
}

From source file:GuavaStopwatch.java

private static void demonstrateStopwatch() {
    Stopwatch stopWatch = new Stopwatch();
    System.out.println("Is stopwatch running? " + stopWatch.isRunning());

    stopWatch.start();//from w  ww  .java  2  s.  co  m

    for (int i = 0; i < 1000; i++) {
        System.out.println("Is stopwatch running? " + stopWatch.isRunning());
    }

    stopWatch.stop();
    System.out.println("Our loop took : " + stopWatch.elapsedTime(TimeUnit.MILLISECONDS) + " milliseconds");
}

From source file:hr.fer.tel.rovkp.lab01.Program.java

public static void zad2(String from, String to) {
    Stopwatch timer = new Stopwatch().start();

    FileReaderWriter frw = new FileReaderWriter();
    try {/*from  ww  w.  j av  a2 s .c o  m*/
        frw.work(from, to, StandardCharsets.ISO_8859_1);
    } catch (URISyntaxException | IOException ex) {
        System.err.println(ex);
    } catch (Exception ex) {
        System.err.println(ex);
    }

    timer.stop();
    System.out.println("Read " + frw.readLinesCount() + " lines from " + frw.readFilesCount() + " files.");
    System.out.println("Program finished in " + timer.elapsedTime(TimeUnit.SECONDS) + " seconds.");
}

From source file:org.apache.drill.exec.store.schedule.AffinityCreator.java

public static <T extends CompleteWork> List<EndpointAffinity> getAffinityMap(List<T> work) {
    Stopwatch watch = new Stopwatch();

    long totalBytes = 0;
    for (CompleteWork entry : work) {
        totalBytes += entry.getTotalBytes();
    }//from   www. j a v a 2 s.c  om

    ObjectFloatOpenHashMap<DrillbitEndpoint> affinities = new ObjectFloatOpenHashMap<DrillbitEndpoint>();
    for (CompleteWork entry : work) {
        for (ObjectLongCursor<DrillbitEndpoint> cursor : entry.getByteMap()) {
            long bytes = cursor.value;
            float affinity = (float) bytes / (float) totalBytes;
            logger.debug("Work: {} Endpoint: {} Bytes: {}", work, cursor.key.getAddress(), bytes);
            affinities.putOrAdd(cursor.key, affinity, affinity);
        }
    }

    List<EndpointAffinity> affinityList = Lists.newLinkedList();
    for (ObjectFloatCursor<DrillbitEndpoint> d : affinities) {
        logger.debug("Endpoint {} has affinity {}", d.key.getAddress(), d.value);
        affinityList.add(new EndpointAffinity(d.key, d.value));
    }

    logger.debug("Took {} ms to get operator affinity", watch.elapsed(TimeUnit.MILLISECONDS));
    return affinityList;
}

From source file:qa.qcri.qnoise.inject.OutlierInjector.java

@Override
public void act(NoiseContext context, HashMap<String, Object> extras) {
    Stopwatch stopwatch = new Stopwatch().start();
    NoiseSpec spec = context.spec;/*  ww  w  .ja  v  a 2s  .  com*/
    DataProfile profile = context.profile;
    NoiseReport report = context.report;

    String[] selectedColumns = spec.filteredColumns;
    Preconditions.checkArgument(selectedColumns.length == 1,
            "Outlier currently only supports one column (univariable).");

    String selectedColumn = selectedColumns[0];
    DataType type = profile.getType(selectedColumn);
    int columnIndex = profile.getColumnIndex(selectedColumn);

    Preconditions.checkArgument(type == DataType.Numerical, "Outlier only applies to numerical data.");

    double perc = spec.percentage;
    int len = (int) Math.floor(perc * profile.getLength());

    Double std = profile.getStandardDeviationOn(selectedColumn);
    Double mean = profile.getMean(selectedColumn);

    Double lmax = mean + 2 * std; // 95 % in the bell
    Double rmax = mean + 5 * std; // (extra 3 * std)

    ModelBase randomModal = ModelFactory.createRandomModel();
    Random random = new Random();
    int index;
    for (int i = 0; i < len; i++) {
        // TODO: should we ignore the point already in the outlier region
        // how to deal with small deviation data?
        index = randomModal.nextIndexWithoutReplacement(0, profile.getLength(), true);
        double u = Math.random() * (rmax - lmax) + lmax;
        double v = random.nextGaussian() + u;
        Pair<Integer, Integer> record = new Pair<>(index, columnIndex);
        tracer.verbose(String.format("[%d, %d] <- %f", index, columnIndex, v));
        report.logChange(record, profile.getCell(index, columnIndex), Double.toString(v));

        while (!profile.set(record, Double.toString(v))) {
            index = randomModal.nextIndexWithoutReplacement(0, profile.getLength(), false);
            record = new Pair<>(index, columnIndex);
        }
    }

    long elapsedTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);
    report.addMetric(NoiseReport.Metric.InjectionTime, elapsedTime);
    stopwatch.stop();
}

From source file:qa.qcri.qnoise.inject.MissingInjector.java

/** {@inheritDoc */
@Override/*  w  w  w  .  j  a v a 2  s .com*/
public void act(NoiseContext context, HashMap<String, Object> extras) {
    Stopwatch stopwatch = new Stopwatch().start();
    NoiseSpec spec = context.spec;
    DataProfile profile = context.profile;
    NoiseReport report = context.report;

    NoiseModel model = spec.model;
    ModelBase randomModel = ModelFactory.createRandomModel();

    ModelBase indexGen;
    if (model == NoiseModel.Random) {
        indexGen = ModelFactory.createRandomModel();
    } else {
        String columnName = spec.filteredColumns[0];
        indexGen = ModelFactory.createHistogramModel(profile, columnName);
    }

    double perc = spec.percentage;

    int len = (int) Math.floor(perc * profile.getLength());
    report.addMetric(NoiseReport.Metric.ChangedItem, len);
    int count = 0;
    while (count < len) {
        int index = indexGen.nextIndex(0, profile.getLength());
        GranularityType granularity = spec.granularity;
        if (granularity == GranularityType.Cell) {
            int cellIndex = randomModel.nextIndex(0, profile.getWidth());
            Pair<Integer, Integer> record = new Pair<>(index, cellIndex);
            report.logChange(record, profile.getCell(record), null);
            String oldValue = profile.getCell(index, cellIndex);
            if (profile.set(record, null))
                tracer.infoChange(new Pair<>(index, cellIndex), oldValue, "null");
            else
                tracer.infoUnchange(new Pair<>(index, cellIndex));
        } else {
            // set the whole tuple to missing
            int width = profile.getWidth();
            for (int i = 0; i < width; i++) {
                Pair<Integer, Integer> record = new Pair<>(index, i);
                report.logChange(record, profile.getCell(record), null);
                profile.set(record, null);
                tracer.verbose(String.format("[%d, %d] <- null", index, i));
            }
        }
        count++;
    }

    long elapsedTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);
    report.addMetric(NoiseReport.Metric.InjectionTime, elapsedTime);
    stopwatch.stop();
}

From source file:qa.qcri.qnoise.inject.DuplicateInjector.java

@Override
public void act(NoiseContext context, HashMap<String, Object> extras) {
    Stopwatch stopwatch = new Stopwatch().start();
    ModelBase indexGen = ModelFactory.createRandomModel();
    double seedperc = context.spec.numberOfSeed;
    double timeperc = context.spec.percentage;

    int nseed = (int) (Math.ceil(context.profile.getLength() * seedperc));
    int ntime = (int) (Math.ceil(context.profile.getLength() * timeperc));

    int count = 0;

    while (count < nseed) {
        int index = indexGen.nextIndex(0, context.profile.getLength());

        for (int i = 0; i < ntime; i++) {
            String[] oldData = context.profile.getReadOnlyTuple(index);
            String[] newData = oldData.clone();
            double[] distance;
            String[] columns = null;
            if (context.spec.filteredColumns != null) {
                columns = context.spec.filteredColumns;
            } else {
                columns = context.profile.getColumnNames();
            }// ww  w.j a  v a2s .  co  m

            if (context.spec.distance != null) {
                distance = context.spec.distance;
                if (distance.length != columns.length) {
                    throw new IllegalArgumentException("Distance has missing or incorrect number of columns.");
                }
            } else {
                distance = new double[columns.length];
            }

            context.profile.append(newData);
            if (Tracer.isVerboseOn()) {
                StringBuilder sb = new StringBuilder("Add ");
                sb.append('[').append(context.profile.getLength() - 1).append("] [ ");
                for (String cell : newData) {
                    sb.append('\'').append(cell).append("\' ");
                }
                sb.append(']');
                tracer.verbose(sb.toString());
            }

            for (int j = 0; j < context.profile.getWidth(); j++) {
                context.report.logInsert(new Pair<>(context.profile.getLength() - 1, j),
                        context.profile.getCell(i, j));
            }

            NoiseHelper.playTheJazz(distance, columns, context.profile, context.profile.getLength() - 1,
                    context.report);
        }
        count++;
    }

    context.report.appendMetric(NoiseReport.Metric.ChangedItem, nseed * ntime);
    context.report.appendMetric(NoiseReport.Metric.PercentageOfDuplicate, timeperc);
    context.report.addMetric(NoiseReport.Metric.InjectionTime, stopwatch.elapsed(TimeUnit.MILLISECONDS));
    context.profile.setDirty();
}

From source file:qa.qcri.qnoise.inject.ErrorNoiseInjector.java

@Override
public void act(NoiseContext context, HashMap<String, Object> extras) {
    Stopwatch stopwatch = new Stopwatch().start();
    NoiseSpec spec = context.spec;/*from  ww w.  j  a v a 2 s  .  c om*/
    DataProfile profile = context.profile;
    NoiseReport report = context.report;

    NoiseModel model = spec.model;
    ModelBase randomModel = ModelFactory.createRandomModel();

    ModelBase indexGen;
    if (model == NoiseModel.Random) {
        indexGen = ModelFactory.createRandomModel();
    } else {
        String columnName = spec.filteredColumns[0];
        indexGen = ModelFactory.createHistogramModel(profile, columnName);
    }

    double perc = spec.percentage;

    int len = (int) Math.floor(perc * profile.getLength());
    report.addMetric(NoiseReport.Metric.ChangedItem, len);
    int count = 0;
    while (count < len) {
        double distance = 0.0;
        int index = indexGen.nextIndex(0, profile.getWidth());
        int cellIndex;

        if (spec.filteredColumns != null) {
            int filteredCellIndex = randomModel.nextIndex(0, spec.filteredColumns.length);
            String filteredCellName = spec.filteredColumns[filteredCellIndex];
            cellIndex = profile.getColumnIndex(filteredCellName);
            if (spec.distance != null) {
                if (spec.distance.length != spec.filteredColumns.length)
                    throw new IllegalArgumentException("Distance has missing or incorrect number of columns.");
                distance = spec.distance[filteredCellIndex];
            }
        } else {
            cellIndex = randomModel.nextIndex(0, profile.getWidth());
        }

        Pair<Integer, Integer> record = new Pair<>(index, cellIndex);
        if (profile.isDirty(record)) {
            continue;
        }

        // change the data.
        NoiseHelper.playTheJazz(distance, profile.getColumnName(cellIndex), profile, index, report);
        count++;
    }

    long elapsedTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);
    report.addMetric(NoiseReport.Metric.InjectionTime, elapsedTime);
    stopwatch.stop();
}

From source file:org.apache.drill.jdbc.test.JdbcTestQueryBase.java

protected static void testQuery(String sql) throws Exception {
    boolean success = false;
    try (Connection conn = connect("jdbc:drill:zk=local")) {
        for (int x = 0; x < 1; x++) {
            Stopwatch watch = new Stopwatch().start();
            Statement s = conn.createStatement();
            ResultSet r = s.executeQuery(sql);
            System.out.println(String.format("QueryId: %s", r.unwrap(DrillResultSet.class).getQueryId()));
            boolean first = true;
            while (r.next()) {
                ResultSetMetaData md = r.getMetaData();
                if (first == true) {
                    for (int i = 1; i <= md.getColumnCount(); i++) {
                        System.out.print(md.getColumnName(i));
                        System.out.print('\t');
                    }/*from  ww  w .j ava 2  s .  c o  m*/
                    System.out.println();
                    first = false;
                }

                for (int i = 1; i <= md.getColumnCount(); i++) {
                    System.out.print(r.getObject(i));
                    System.out.print('\t');
                }
                System.out.println();
            }

            System.out.println(
                    String.format("Query completed in %d millis.", watch.elapsed(TimeUnit.MILLISECONDS)));
        }

        System.out.println("\n\n\n");
        success = true;
    } finally {
        if (!success) {
            Thread.sleep(2000);
        }
    }
}