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:nl.knaw.huygens.timbuctoo.tools.importer.neww.GenreUpdater.java

public static void main(String[] args) throws Exception {
    Stopwatch stopWatch = Stopwatch.createStarted();

    // Handle commandline arguments
    String directory = (args.length > 0) ? args[0] : DEFAULT_DIR_NAME;

    Repository repository = null;/*ww  w  . j  ava  2  s.c  om*/
    IndexManager indexManager = null;
    try {
        Injector injector = ToolsInjectionModule.createInjector();
        repository = injector.getInstance(Repository.class);
        indexManager = injector.getInstance(IndexManager.class);
        Change change = new Change(Constants.IMPORT_USER, "neww");

        GenreUpdater importer = new GenreUpdater(repository, change);
        importer.handleFile(new File(directory, GENRE_FILE_NAME), 2, false);
    } finally {
        if (indexManager != null) {
            indexManager.close();
        }
        if (repository != null) {
            repository.close();
        }
        LOG.info("Time used: {}", stopWatch);
    }
}

From source file:ch.ethz.tik.graphgenerator.GraphGenerator.java

public static void main(String[] args) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    Graph graph = generateGraph();/*from w  w  w.j  a v a2 s . c om*/
    stopwatch.elapsed(TimeUnit.MILLISECONDS);
    System.out.println("Reading and creating graph took: " + stopwatch);

    createExampleRoutes(graph);

    stopwatch = Stopwatch.createStarted();
    GraphSerializerUtil.serializeGraph(graph, SERIALIZED_FILE_GRAPH);
    stopwatch.elapsed(TimeUnit.MILLISECONDS);
    System.out.println("Serialized graph in " + stopwatch);
}

From source file:de.jamilsoufan.panalyzer.app.Panalyzer.java

/**
 * Entry point of the application/*from   w ww .j  a v  a 2s.  c o m*/
 *
 * @param args Command line arguments
 */
public static void main(String[] args) {
    LOGGER.info("Starting panalyzer for: {}", Analyzer.START_DIR);
    Stopwatch stopwatch = Stopwatch.createStarted();

    Runner runnner = new Runner();
    runnner.runForrestRun();

    stopwatch.stop();
    LOGGER.info("Finish. Analyzed folders: {} / files: {}. Duration: {}", Analyzer.countFolders,
            Analyzer.countFiles, stopwatch);
}

From source file:com.jejking.hh.nord.app.CreateSpatialDrucksachenRepository.java

/**
 * Runs the main importer logic. Supply two parameters: directory where
 * the Neo4j database is located, directory where the serialised {@link RawDrucksache}
 * instances are to be found, each in its own file.
 * //from   w  w  w .ja  v  a  2s. co m
 * @param args
 */
public static void main(String[] args) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    GraphDatabaseService graph = new GraphDatabaseFactory().newEmbeddedDatabase(args[0]);
    registerShutdownHook(graph);
    System.out.println("Started graph database after " + stopwatch.elapsed(TimeUnit.SECONDS) + " seconds");

    DrucksachenGazetteerKeywordMatcherFactory matcherFactory = new DrucksachenGazetteerKeywordMatcherFactory();
    ImmutableMap<String, DrucksachenGazetteerKeywordMatcher> matchersMap = matcherFactory
            .createKeywordMatchersFromGazetteer(graph,
                    ImmutableList.of(GazetteerEntryTypes.NAMED_AREA, GazetteerEntryTypes.STREET,
                            GazetteerEntryTypes.SCHOOL, GazetteerEntryTypes.HOSPITAL,
                            GazetteerEntryTypes.CINEMA, GazetteerEntryTypes.UNIVERSITY));

    ImportAndMatch importer = new ImportAndMatch(matchersMap);
    System.out.println("Initialised matchers after " + stopwatch.elapsed(TimeUnit.SECONDS) + " seconds");

    importer.createDrucksachenIndexes(graph);
    System.out.println(
            "Created indexes for Drucksachen after " + stopwatch.elapsed(TimeUnit.SECONDS) + " seconds");

    File drucksachenDirectory = new File(args[1]);
    importer.writeToNeo(Arrays.asList(drucksachenDirectory.listFiles()), graph);
    System.out.println("Completed import after " + stopwatch.elapsed(TimeUnit.SECONDS) + " seconds");
}

From source file:com.paolodragone.wsn.disambiguation.WsnDisambiguator.java

public static void main(String[] args) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    try {//from w  w  w  . j a v  a  2  s . co  m
        System.out.println("Loading...");

        // Readers
        WsnConfiguration configuration = WsnConfiguration.getInstance();
        Reader sensesFileReader = Files.newBufferedReader(configuration.getSensesFilePath());
        Reader synonymsFileReader = Files.newBufferedReader(configuration.getSynonymsFilePath());
        Reader sensesSynonymsFileReader = Files.newBufferedReader(configuration.getSensesSynonymsFilePath());
        Reader termsFileReader = Files.newBufferedReader(configuration.getTermsFilePath());
        Reader termWeightsFileReader = Files.newBufferedReader(configuration.getTermWeightsFilePath());

        // Get sense Stream
        SensesDataSet sensesDataSet = new SensesDataSet();
        SensesDataSet sensesDataSetView;
        sensesDataSetView = sensesDataSet.getView(sensesDataSet.excludeColumns(SenseColumn.Gloss));
        Stream<Sense> senseStream = sensesDataSetView.getEntityStream(sensesFileReader).parallel();
        senseStream = Senses.filterValidSenses(senseStream);
        Collection<Sense> senses = DStreamSupport.toList(senseStream);
        Map<Integer, Sense> senseMap = DCollections.collectionToMap(senses, Sense::getId, new HashMap<>());

        // Set terms
        TermsDataSet termsDataSet = new TermsDataSet();
        TermsDataSet termsDataSetView;
        termsDataSetView = termsDataSet.getView(termsDataSet.excludeColumns(TermsDataSet.TermColumn.Word));
        Stream<Term> termStream = Terms.filterValidTerms(termsDataSetView.getEntityStream(termsFileReader));
        TermsDataSet.setTerms(senseMap, termStream);

        // Set synonyms
        SynonymsDataSet synonymsDataSet = new SynonymsDataSet();
        Collection<Synonym> synonyms = DStreamSupport
                .toList(synonymsDataSet.getEntityStream(synonymsFileReader));
        Map<Integer, Synonym> synonymMap = SynonymsDataSet.getSynonymMap(synonyms);
        SensesSynonymsDataSet sensesSynonymsDataSet = new SensesSynonymsDataSet();
        Stream<SenseSynonym> senseSynonymStream = sensesSynonymsDataSet
                .getEntityStream(sensesSynonymsFileReader);
        SensesSynonymsDataSet.setSynonyms(senseMap, synonymMap, senseSynonymStream);
        synonyms = null;
        synonymMap = null;

        // Get term weights
        TermWeightsDataSet termWeightsDataSet = new TermWeightsDataSet();
        Stream<TermWeight> termWeightStream = termWeightsDataSet.getEntityStream(termWeightsFileReader);
        Map<String, Double> termWeightMap = TermWeightsDataSet.getTermWeightMap(termWeightStream);

        System.out.println("Done.");

        WsnDisambiguator disambiguator = new WsnDisambiguator(senses, termWeightMap, defaultContextDepth);
        termWeightMap = null;

        DisambiguatedTermsPrinter disambiguatedTermsPrinter = new DisambiguatedTermsPrinter();
        disambiguator.epochEvent.addEventHandler(disambiguatedTermsPrinter::printEpoch);
        disambiguator.seenTermEvent.addEventHandler(disambiguatedTermsPrinter::incrementTerms);
        disambiguator.disambiguatedTermEvent
                .addEventHandler(disambiguatedTermsPrinter::incrementDisambiguatedTerms);
        disambiguator.changedEvent.addEventHandler(disambiguatedTermsPrinter::changed);

        /*
                    CountResult countResult = disambiguator.countTerms();
                    System.out.println("Total terms: " + countResult.getTotalTerms());
                    System.out.println("Valid terms: " + countResult.getValidTerms());
                    System.out.println("Unsolved terms: " + countResult.getUnsolvedTerms());
                    System.out.println("Monosemous terms: " + countResult.getMonosemousTerms());
                    System.out.println("Ambiguous terms: " + countResult.getAmbiguousTerms());
        */

        List<SemanticEdge> semanticNetwork = disambiguator.buildSemanticNetwork();
        Writer semanticNetworkFileWriter = Files.newBufferedWriter(configuration.getSemanticNetworkFilePath());

        SemanticNetworkDataSet semanticNetworkDataSet = new SemanticNetworkDataSet();
        semanticNetworkDataSet.writeEntities(semanticNetwork.stream(), semanticNetworkFileWriter);

    } catch (Exception e) {
        e.printStackTrace();
    }
    long elapsed = stopwatch.stop().elapsed(TimeUnit.MINUTES);
    System.out.println("\nTotal time: " + elapsed + " min");
}

From source file:nl.knaw.huygens.timbuctoo.tools.importer.LocationUpdater.java

public static void main(String[] args) throws Exception {
    Stopwatch stopWatch = Stopwatch.createStarted();

    String vreId = (args.length > 0) ? args[0] : DEFAULT_VRE_ID;
    LOG.info("VRE: {}", vreId);

    String directoryName = (args.length > 1) ? args[1] : IMPORT_DIRECTORY_NAME + vreId + "/";
    File directory = new File(directoryName);
    checkArgument(directory.isDirectory(), "Not a directory: %s", directory);

    Injector injector = ToolsInjectionModule.createInjector();
    Repository repository = injector.getInstance(Repository.class);
    IndexManager indexManager = injector.getInstance(IndexManager.class);

    try {/*from www.  jav a  2  s .  co  m*/
        LocationUpdater updater = new LocationUpdater(repository, indexManager, vreId);
        updater.handleFile(new File(directory, "baselocation-update.json"), false);
        int errors = updater.displayErrorSummary();
        if (errors == 0) {
            updater.handleFile(new File(directory, "baselocation-update.json"), true);
            updater.displayStatus();
        }
    } finally {
        indexManager.close();
        repository.close();
        LOG.info("Time used: {}", stopWatch);
    }
}

From source file:com.google.cloud.genomics.gatk.htsjdk.SamReaderExample.java

public static void main(String[] args) {
    try {//from   www  .  ja v a  2s . co m
        SamReaderFactory factory = SamReaderFactory.makeDefault();

        // If it was a file, we would open like so:
        // factory.open(new File("~/testdata/htsjdk/samtools/uncompressed.sam"));
        // For API access we use SamInputResource constructed from a URL:
        SamReader reader = factory.open(SamInputResource.of(new URL(GA4GH_URL)));

        Stopwatch timer = Stopwatch.createStarted();
        int processedReads = 0;
        for (@SuppressWarnings("unused")
        final SAMRecord samRecord : reader) {
            processedReads++;
        }
        final long elapsed = timer.elapsed(TimeUnit.MILLISECONDS);
        if (processedReads > 0 && elapsed > 0) {
            System.out.println("Processed " + processedReads + " reads in " + timer + ". Speed: "
                    + (processedReads * 1000) / elapsed + " reads/sec");
        } else {
            System.out.println("Nothing processed or not enough reads for timing stats.");
        }
        reader.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.google.devtools.build.android.AndroidCompiledResourceMergingAction.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);

    Preconditions.checkNotNull(options.primaryData);
    Preconditions.checkNotNull(options.primaryManifest);
    Preconditions.checkNotNull(options.manifestOutput);
    Preconditions.checkNotNull(options.classJarOutput);

    try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("android_resource_merge_tmp");
            ExecutorServiceCloser executorService = ExecutorServiceCloser.createWithFixedPoolOf(15)) {
        Path tmp = scopedTmp.getPath();
        Path generatedSources = tmp.resolve("generated_resources");
        Path processedManifest = tmp.resolve("manifest-processed/AndroidManifest.xml");

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

        String packageForR = options.packageForR;
        if (packageForR == null) {
            packageForR = Strings/*  w ww  .  j  a  v  a  2  s . c  o  m*/
                    .nullToEmpty(VariantConfiguration.getManifestPackage(options.primaryManifest.toFile()));
        }
        AndroidResourceClassWriter resourceClassWriter = AndroidResourceClassWriter
                .createWith(aaptConfigOptions.androidJar, generatedSources, packageForR);
        resourceClassWriter.setIncludeClassFile(true);
        resourceClassWriter.setIncludeJavaFile(false);

        AndroidResourceMerger.mergeCompiledData(options.primaryData, options.primaryManifest,
                options.directData, options.transitiveData, resourceClassWriter,
                options.throwOnResourceConflict, executorService);
        logger.fine(String.format("Merging finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

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

        // Until enough users with manifest placeholders migrate to the new manifest merger,
        // we need to replace ${applicationId} and ${packageName} with options.packageForR to make
        // the manifests compatible with the old manifest merger.
        processedManifest = AndroidManifestProcessor.with(stdLogger).processLibraryManifest(options.packageForR,
                options.primaryManifest, processedManifest);

        Files.createDirectories(options.manifestOutput.getParent());
        Files.copy(processedManifest, options.manifestOutput);
    } catch (MergeConflictException e) {
        logger.log(Level.SEVERE, e.getMessage());
        System.exit(1);
    } catch (MergingException e) {
        logger.log(Level.SEVERE, "Error during merging resources", e);
        throw e;
    } catch (AndroidManifestProcessor.ManifestProcessingException e) {
        System.exit(1);
    } 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:ec.jwsacruncher.App.java

/**
 * @param args the command line arguments
 *///from  w  w  w.  ja v  a  2  s. c  om
public static void main(String[] args) {
    Stopwatch stopwatch = Stopwatch.createStarted();

    Entry<File, WsaConfig> config = ArgsDecoder.decodeArgs(args);
    if (config == null) {
        System.out.println("Wrong arguments");
        return;
    }

    if (args == null || args.length == 0) {
        return;
    }

    if (config.getValue() == null) {
        return;
    }

    loadResources();
    enableDiagnostics(config.getValue().Matrix);

    try (FileWorkspace ws = FileWorkspace.open(config.getKey().toPath())) {
        process(ws, ProcessingContext.getActiveContext(), config.getValue());
    } catch (IOException ex) {
        log.log(Level.SEVERE, null, ex);
    }

    System.out.println("Total processing time: " + stopwatch.elapsed(TimeUnit.SECONDS) + "s");
}

From source file:grakn.core.server.Grakn.java

public static void main(String[] args) {
    Thread.setDefaultUncaughtExceptionHandler(
            (Thread t, Throwable e) -> LOG.error(ErrorMessage.UNCAUGHT_EXCEPTION.getMessage(t.getName()), e));

    try {//from   w  w  w  . j av a 2s . c o m
        String graknPidFileProperty = Optional.ofNullable(SystemProperty.GRAKN_PID_FILE.value()).orElseThrow(
                () -> new RuntimeException(ErrorMessage.GRAKN_PIDFILE_SYSTEM_PROPERTY_UNDEFINED.getMessage()));

        Path pidfile = Paths.get(graknPidFileProperty);
        PIDManager pidManager = new PIDManager(pidfile);
        pidManager.trackGraknPid();

        // Start Server with timer
        Stopwatch timer = Stopwatch.createStarted();
        boolean benchmark = parseBenchmarkArg(args);
        Server server = ServerFactory.createServer(benchmark);
        server.start();

        LOG.info("Grakn started in {}", timer.stop());
    } catch (RuntimeException | IOException e) {
        LOG.error(ErrorMessage.UNCAUGHT_EXCEPTION.getMessage(e.getMessage()), e);
        System.err.println(ErrorMessage.UNCAUGHT_EXCEPTION.getMessage(e.getMessage()));
    }
}