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.google.devtools.build.android.GenerateRobolectricResourceSymbolsAction.java

public static void main(String[] args) throws Exception {

    final Stopwatch timer = Stopwatch.createStarted();
    OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class, AaptConfigOptions.class);
    optionsParser.enableParamsFileSupport(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault()));
    optionsParser.parseAndExitUponError(args);
    AaptConfigOptions aaptConfigOptions = optionsParser.getOptions(AaptConfigOptions.class);
    Options options = optionsParser.getOptions(Options.class);

    try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("robolectric_resources_tmp")) {
        Path tmp = scopedTmp.getPath();
        Path generatedSources = Files.createDirectories(tmp.resolve("generated_resources"));
        // The reported availableProcessors may be higher than the actual resources
        // (on a shared system). On the other hand, a lot of the work is I/O, so it's not completely
        // CPU bound. As a compromise, divide by 2 the reported availableProcessors.
        int numThreads = Math.max(1, Runtime.getRuntime().availableProcessors() / 2);
        ListeningExecutorService executorService = MoreExecutors
                .listeningDecorator(Executors.newFixedThreadPool(numThreads));
        try (Closeable closeable = ExecutorServiceCloser.createWith(executorService)) {

            logger.fine(String.format("Setup finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

            final PlaceholderIdFieldInitializerBuilder robolectricIds = PlaceholderIdFieldInitializerBuilder
                    .from(aaptConfigOptions.androidJar);
            ParsedAndroidData.loadedFrom(options.data, executorService, AndroidDataDeserializer.create())
                    .writeResourcesTo(new AndroidResourceSymbolSink() {

                        @Override
                        public void acceptSimpleResource(ResourceType type, String name) {
                            robolectricIds.addSimpleResource(type, name);
                        }/*  w ww  . j  a v a2 s  .c  o  m*/

                        @Override
                        public void acceptPublicResource(ResourceType type, String name,
                                Optional<Integer> value) {
                            robolectricIds.addPublicResource(type, name, value);
                        }

                        @Override
                        public void acceptStyleableResource(FullyQualifiedName key,
                                Map<FullyQualifiedName, Boolean> attrs) {
                            robolectricIds.addStyleableResource(key, attrs);
                        }
                    });

            final RClassGenerator generator = RClassGenerator.with(generatedSources, robolectricIds.build(),
                    false);

            List<SymbolFileProvider> libraries = new ArrayList<>();
            for (DependencyAndroidData dataDep : options.data) {
                SymbolFileProvider library = dataDep.asSymbolFileProvider();
                libraries.add(library);
            }
            List<ListenableFuture<Boolean>> writeSymbolsTask = new ArrayList<>();
            for (final Entry<String, Collection<ListenableFuture<ResourceSymbols>>> librarySymbolEntry : ResourceSymbols
                    .loadFrom(libraries, executorService, null).asMap().entrySet()) {
                writeSymbolsTask
                        .add(executorService.submit(new WriteLibraryRClass(librarySymbolEntry, generator)));
            }
            FailedFutureAggregator.forIOExceptionsWithMessage("Errors writing symbols.")
                    .aggregateAndMaybeThrow(writeSymbolsTask);
        }

        logger.fine(String.format("Merging finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        AndroidResourceOutputs.createClassJar(generatedSources, options.classJarOutput);
        logger.fine(String.format("Create classJar finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

    } catch (Exception e) {
        logger.log(Level.SEVERE, "Unexpected", e);
        throw e;
    }
    logger.fine(String.format("Resources merged in %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
}

From source file:com.google.devtools.build.android.AndroidResourceProcessingAction.java

public static void main(String[] args) throws Exception {
    final Stopwatch timer = Stopwatch.createStarted();
    OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class, AaptConfigOptions.class);
    optionsParser.parseAndExitUponError(args);
    aaptConfigOptions = optionsParser.getOptions(AaptConfigOptions.class);
    options = optionsParser.getOptions(Options.class);

    final AndroidResourceProcessor resourceProcessor = new AndroidResourceProcessor(STD_LOGGER);
    try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("android_resources_tmp")) {
        final Path tmp = scopedTmp.getPath();
        final Path mergedAssets = tmp.resolve("merged_assets");
        final Path mergedResources = tmp.resolve("merged_resources");
        final Path filteredResources = tmp.resolve("resources-filtered");
        final Path densityManifest = tmp.resolve("manifest-filtered/AndroidManifest.xml");
        final Path processedManifest = tmp.resolve("manifest-processed/AndroidManifest.xml");
        final Path dummyManifest = tmp.resolve("manifest-aapt-dummy/AndroidManifest.xml");

        Path generatedSources = null;
        if (options.srcJarOutput != null || options.rOutput != null || options.symbolsOut != null) {
            generatedSources = tmp.resolve("generated_resources");
        }/*from   w  ww . ja v  a  2 s .co m*/

        logger.fine(String.format("Setup finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        List<DependencyAndroidData> data = ImmutableSet.<DependencyAndroidData>builder()
                .addAll(options.directData).addAll(options.transitiveData).build().asList();

        final MergedAndroidData mergedData = resourceProcessor.mergeData(options.primaryData,
                options.directData, options.transitiveData, mergedResources, mergedAssets, selectPngCruncher(),
                options.packageType, options.symbolsOut);

        logger.fine(String.format("Merging finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        final DensityFilteredAndroidData filteredData = mergedData.filter(
                new DensitySpecificResourceFilter(options.densities, filteredResources, mergedResources),
                new DensitySpecificManifestProcessor(options.densities, densityManifest));

        logger.fine(String.format("Density filtering finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        MergedAndroidData processedData = resourceProcessor.processManifest(options.packageType,
                options.packageForR, options.applicationId, options.versionCode, options.versionName,
                filteredData, processedManifest);

        // Write manifestOutput now before the dummy manifest is created.
        if (options.manifestOutput != null) {
            resourceProcessor.copyManifestToOutput(processedData, options.manifestOutput);
        }

        if (options.packageType == VariantType.LIBRARY) {
            resourceProcessor.writeDummyManifestForAapt(dummyManifest, options.packageForR);
            processedData = new MergedAndroidData(processedData.getResourceDir(), processedData.getAssetDir(),
                    dummyManifest);
        }

        resourceProcessor.processResources(aaptConfigOptions.aapt, aaptConfigOptions.androidJar,
                aaptConfigOptions.buildToolsVersion, options.packageType, aaptConfigOptions.debug,
                options.packageForR, new FlagAaptOptions(aaptConfigOptions), aaptConfigOptions.resourceConfigs,
                aaptConfigOptions.splits, processedData, data, generatedSources, options.packagePath,
                options.proguardOutput, options.mainDexProguardOutput,
                options.resourcesOutput != null
                        ? processedData.getResourceDir().resolve("values").resolve("public.xml")
                        : null,
                options.dataBindingInfoOut);
        logger.fine(String.format("aapt finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        if (options.srcJarOutput != null) {
            resourceProcessor.createSrcJar(generatedSources, options.srcJarOutput,
                    VariantType.LIBRARY == options.packageType);
        }
        if (options.rOutput != null) {
            resourceProcessor.copyRToOutput(generatedSources, options.rOutput,
                    VariantType.LIBRARY == options.packageType);
        }
        if (options.resourcesOutput != null) {
            resourceProcessor.createResourcesZip(processedData.getResourceDir(), processedData.getAssetDir(),
                    options.resourcesOutput, false /* compress */);
        }
        logger.fine(String.format("Packaging finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
    } catch (MergingException e) {
        logger.log(java.util.logging.Level.SEVERE, "Error during merging resources", e);
        throw e;
    } catch (IOException | InterruptedException | LoggedErrorException | UnrecognizedSplitsException e) {
        logger.log(java.util.logging.Level.SEVERE, "Error during processing resources", e);
        throw e;
    } catch (Exception e) {
        logger.log(java.util.logging.Level.SEVERE, "Unexpected", e);
        throw e;
    } finally {
        resourceProcessor.shutdown();
    }
    logger.fine(String.format("Resources processed in %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
}

From source file:com.google.devtools.build.android.ResourceShrinkerAction.java

public static void main(String[] args) throws Exception {
    final Stopwatch timer = Stopwatch.createStarted();
    // Parse arguments.
    OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class, AaptConfigOptions.class);
    optionsParser.parseAndExitUponError(args);
    aaptConfigOptions = optionsParser.getOptions(AaptConfigOptions.class);
    options = optionsParser.getOptions(Options.class);

    AndroidResourceProcessor resourceProcessor = new AndroidResourceProcessor(stdLogger);
    // Setup temporary working directories.
    try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("resource_shrinker_tmp")) {
        Path working = scopedTmp.getPath();
        final Path resourceFiles = working.resolve("resource_files");

        final Path shrunkResources = working.resolve("shrunk_resources");

        // Gather package list from manifests.
        Set<String> resourcePackages = getManifestPackages(options.primaryManifest,
                options.dependencyManifests);
        resourcePackages.addAll(options.resourcePackages);

        // Expand resource files zip into working directory.
        try (ZipInputStream zin = new ZipInputStream(new FileInputStream(options.resourcesZip.toFile()))) {
            ZipEntry entry;/*from  w  ww.  ja  va2 s .  c o m*/
            while ((entry = zin.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    Path output = resourceFiles.resolve(entry.getName());
                    Files.createDirectories(output.getParent());
                    try (FileOutputStream fos = new FileOutputStream(output.toFile())) {
                        ByteStreams.copy(zin, fos);
                    }
                }
            }
        }

        // Shrink resources.
        ResourceUsageAnalyzer resourceShrinker = new ResourceUsageAnalyzer(resourcePackages, options.rTxt,
                options.shrunkJar, options.primaryManifest, options.proguardMapping,
                resourceFiles.resolve("res"), options.log);

        resourceShrinker.shrink(shrunkResources);
        logger.fine(
                String.format("Shrinking resources finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        Path generatedSources = null;
        if (options.rTxtOutput != null) {
            generatedSources = working.resolve("generated_resources");
        }

        // Build ap_ with shrunk resources.
        resourceProcessor.processResources(aaptConfigOptions.aapt, aaptConfigOptions.androidJar,
                aaptConfigOptions.buildToolsVersion, VariantType.DEFAULT, aaptConfigOptions.debug,
                null /* packageForR */, new FlagAaptOptions(aaptConfigOptions),
                aaptConfigOptions.resourceConfigs, aaptConfigOptions.splits,
                new MergedAndroidData(shrunkResources, resourceFiles.resolve("assets"),
                        options.primaryManifest),
                ImmutableList.<DependencyAndroidData>of() /* libraries */, generatedSources, options.shrunkApk,
                null /* proguardOutput */, null /* mainDexProguardOutput */, null /* publicResourcesOut */,
                null /* dataBindingInfoOut */);
        if (options.shrunkResources != null) {
            resourceProcessor.createResourcesZip(shrunkResources, resourceFiles.resolve("assets"),
                    options.shrunkResources, false /* compress */);
        }
        if (options.rTxtOutput != null) {
            resourceProcessor.copyRToOutput(generatedSources, options.rTxtOutput,
                    options.packageType == VariantType.LIBRARY);
        }
        logger.fine(String.format("Packing resources finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Error shrinking resources", e);
        throw e;
    } finally {
        resourceProcessor.shutdown();
    }
}

From source file:org.cinchapi.concourse.shell.ConcourseShell.java

/**
 * Run the program...//  ww  w .  jav a 2s .c o m
 * 
 * @param args - see {@link Options}
 * @throws IOException
 */
public static void main(String... args) throws IOException {
    ConsoleReader console = new ConsoleReader();
    console.setExpandEvents(false);
    Options opts = new Options();
    JCommander parser = new JCommander(opts, args);
    parser.setProgramName("concourse-shell");
    if (opts.help) {
        parser.usage();
        System.exit(1);
    }
    if (Strings.isNullOrEmpty(opts.password)) {
        opts.password = console.readLine("Password [" + opts.username + "]: ", '*');
    }
    try {
        Concourse concourse = Concourse.connect(opts.host, opts.port, opts.username, opts.password,
                opts.environment);

        final String env = concourse.getServerEnvironment();

        CommandLine.displayWelcomeBanner();
        Binding binding = new Binding();
        GroovyShell shell = new GroovyShell(binding);

        Stopwatch watch = Stopwatch.createUnstarted();
        console.println("Client Version " + Version.getVersion(ConcourseShell.class));
        console.println("Server Version " + concourse.getServerVersion());
        console.println("");
        console.println("Connected to the '" + env + "' environment.");
        console.println("");
        console.println("Type HELP for help.");
        console.println("Type EXIT to quit.");
        console.println("Use TAB for completion.");
        console.println("");
        console.setPrompt(MessageFormat.format("[{0}/cash]$ ", env));
        console.addCompleter(new StringsCompleter(getAccessibleApiMethodsUsingShortSyntax()));

        final List<String> methods = Lists.newArrayList(getAccessibleApiMethods());
        String line;
        while ((line = console.readLine().trim()) != null) {
            line = SyntaxTools.handleShortSyntax(line, methods);
            binding.setVariable("concourse", concourse);
            binding.setVariable("eq", Operator.EQUALS);
            binding.setVariable("ne", Operator.NOT_EQUALS);
            binding.setVariable("gt", Operator.GREATER_THAN);
            binding.setVariable("gte", Operator.GREATER_THAN_OR_EQUALS);
            binding.setVariable("lt", Operator.LESS_THAN);
            binding.setVariable("lte", Operator.LESS_THAN_OR_EQUALS);
            binding.setVariable("bw", Operator.BETWEEN);
            binding.setVariable("regex", Operator.REGEX);
            binding.setVariable("nregex", Operator.NOT_REGEX);
            binding.setVariable("lnk2", Operator.LINKS_TO);
            binding.setVariable("date", STRING_TO_TIME);
            binding.setVariable("time", STRING_TO_TIME);
            binding.setVariable("where", WHERE);
            binding.setVariable("tag", STRING_TO_TAG);
            if (line.equalsIgnoreCase("exit")) {
                concourse.exit();
                System.exit(0);
            } else if (line.equalsIgnoreCase("help") || line.equalsIgnoreCase("man")) {
                Process p = Runtime.getRuntime()
                        .exec(new String[] { "sh", "-c", "echo \"" + HELP_TEXT + "\" | less > /dev/tty" });
                p.waitFor();
            } else if (containsBannedCharSequence(line)) {
                System.err.println(
                        "Cannot complete command because " + "it contains an illegal character sequence.");
            } else if (Strings.isNullOrEmpty(line)) { // CON-170
                continue;
            } else {
                watch.reset().start();
                Object value = null;
                try {
                    value = shell.evaluate(line, "ConcourseShell");
                    watch.stop();
                    if (value != null) {
                        System.out.println(
                                "Returned '" + value + "' in " + watch.elapsed(TimeUnit.MILLISECONDS) + " ms");
                    } else {
                        System.out.println("Completed in " + watch.elapsed(TimeUnit.MILLISECONDS) + " ms");
                    }
                } catch (Exception e) {
                    if (e.getCause() instanceof TTransportException) {
                        die(e.getMessage());
                    } else if (e.getCause() instanceof TSecurityException) {
                        die("A security change has occurred and your " + "session cannot continue");
                    } else {
                        System.err.print("ERROR: " + e.getMessage());
                    }
                }

            }
            System.out.print("\n");
        }
    } catch (Exception e) {
        if (e.getCause() instanceof TTransportException) {
            die("Unable to connect to " + opts.username + "@" + opts.host + ":" + opts.port
                    + " with the specified password");
        } else if (e.getCause() instanceof TSecurityException) {
            die("Invalid username/password combination.");
        } else {
            die(e.getMessage());
        }
    } finally {
        try {
            TerminalFactory.get().restore();
        } catch (Exception e) {
            die(e.getMessage());
        }
    }

}

From source file:de.unentscheidbar.csv2.ProfileMe.java

static long operation() throws Exception {

    Stopwatch sw = Stopwatch.createStarted();
    long ops = 0;
    while (sw.elapsed(TimeUnit.SECONDS) < 1) {
        ops++;/*from   w w  w .  j  a v a 2s . co m*/
        for (CsvRow row : CsvFormat.defaultFormat().parser().parse(csv)) {
            if (row.asList().size() < 0)
                throw new AssertionError();
        }
        // for ( CSVRecord row : CSVFormat.DEFAULT.parse( new StringReader( csv ) ) ) {
        // if ( row.size() < 0 ) throw new AssertionError();
        // }
    }
    return ops;
}

From source file:org.opendaylight.protocol.bgp.rib.impl.CheckUtil.java

public static void checkReceivedMessages(final SimpleSessionListener listener, final int numberOfMessages)
        throws ReadFailedException {
    Stopwatch sw = Stopwatch.createStarted();
    while (sw.elapsed(TimeUnit.SECONDS) <= TIMEOUT) {
        if (listener.getListMsg().size() != numberOfMessages) {
            Uninterruptibles.sleepUninterruptibly(SLEEP_UNINTERRUPTIBLY, TimeUnit.MILLISECONDS);
        } else {/*from w ww . j  a v a2 s  . c  om*/
            return;
        }
    }
    Assert.fail();
}

From source file:ch.oakmountain.tpa.solver.TPAUtil.java

public static void stopStopWatch(Stopwatch stopwatch, String message) {
    stopwatch.stop();// w  w w. j  a  v  a2  s . c  o  m
    long secsBuildModel = stopwatch.elapsed(TimeUnit.MILLISECONDS);
    LOGGER.info("TIME TO " + message + ": " + stopwatch);
}

From source file:org.opendaylight.protocol.bgp.rib.impl.CheckUtil.java

public static <R, T extends DataObject> R readData(final DataBroker dataBroker, final InstanceIdentifier<T> iid,
        final Function<T, R> function) throws ReadFailedException {
    AssertionError lastError = null;
    final Stopwatch sw = Stopwatch.createStarted();
    while (sw.elapsed(TimeUnit.SECONDS) <= TIMEOUT) {
        try (final ReadOnlyTransaction tx = dataBroker.newReadOnlyTransaction()) {
            final Optional<T> data = tx.read(LogicalDatastoreType.OPERATIONAL, iid).checkedGet();
            if (data.isPresent()) {
                try {
                    return function.apply(data.get());
                } catch (final AssertionError e) {
                    lastError = e;// ww w .ja  v a2 s.co m
                    Uninterruptibles.sleepUninterruptibly(SLEEP_FOR, TimeUnit.MILLISECONDS);
                }
            }
        }
    }
    Assert.fail(lastError.getMessage());
    throw lastError;
}

From source file:ezbake.data.common.LoggingUtils.java

public static void stopAndLogStopWatch(Logger logger, Stopwatch watch, String name) {
    watch.stop();/*from w w w .ja  v a  2 s  .c  om*/
    logger.info("{}|{} miliseconds", name, watch.elapsed(TimeUnit.MILLISECONDS));
}

From source file:ezbake.data.common.LoggingUtils.java

public static void logResetAndStartStopWatch(Logger logger, Stopwatch watch, String name) {
    watch.stop();//from w  ww  .  jav  a 2  s . c  o  m
    logger.info("{}|{} miliseconds", name, watch.elapsed(TimeUnit.MILLISECONDS));
    watch.reset();
    watch.start();
}