List of usage examples for org.apache.commons.lang3.time StopWatch StopWatch
public StopWatch()
Constructor.
From source file:net.sf.gazpachoquest.exporter.ExporterRunner.java
public static void main(final String... args) throws IOException { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("exporter-datasource-context.xml", "exporter-jpa-context.xml", "services-context.xml", "facades-context.xml", "components-context.xml"); Exporter exporter = ctx.getBean(Exporter.class); StopWatch stopWatch = new StopWatch(); logger.info("Exporting questionnaire definition"); stopWatch.start();/* w w w.jav a 2 s . c om*/ exporter.doExport(); stopWatch.stop(); logger.info("Export process ended in {} {}", stopWatch.getTime(), "ms"); ctx.close(); }
From source file:net.sf.gazpachoquest.importer.ImporterRunner.java
public static void main(final String... args) throws IOException { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("importer-datasource-context.xml", "importer-jpa-context.xml", "services-context.xml", "facades-context.xml", "components-context.xml"); Importer populator = ctx.getBean(Importer.class); StopWatch stopWatch = new StopWatch(); logger.info("Importing questionnaire definitions"); stopWatch.start();//w w w .ja va2 s .com populator.doImport(); stopWatch.stop(); logger.info("Import process ended in {} {}", stopWatch.getTime(), "ms"); ctx.close(); }
From source file:net.sf.gazpachoquest.dbpopulator.DBPopulatorRunner.java
public static void main(final String... args) { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( "dbpopulator-datasource-context.xml", "dbpopulator-jpa-context.xml", "services-context.xml", "facades-context.xml", "components-context.xml"); DBPopulator populator = ctx.getBean(DBPopulator.class); StopWatch stopWatch = new StopWatch(); logger.info("Populating database"); stopWatch.start();//from w w w . ja v a 2 s . co m ShiroLogin.login(); populator.populate(); stopWatch.stop(); ShiroLogin.logout(); logger.info("Database populated in {} {}", stopWatch.getTime(), "ms"); ctx.close(); }
From source file:chibi.gemmaanalysis.cli.deprecated.AddExperimentalDesignCLI.java
/** * @param args//from w ww . j a v a 2s . c o m */ public static void main(String[] args) { AddExperimentalDesignCLI p = new AddExperimentalDesignCLI(); StopWatch watch = new StopWatch(); watch.start(); try { Exception ex = p.doWork(args); if (ex != null) { ex.printStackTrace(); } watch.stop(); log.info("Total run time: " + watch.getTime()); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:chibi.gemmaanalysis.OutlierDetectionTestCli.java
/** * @param args//from w w w. ja va 2s . co m */ public static void main(String[] args) { OutlierDetectionTestCli testCli = new OutlierDetectionTestCli(); StopWatch watch = new StopWatch(); watch.start(); try { Exception ex = testCli.doWork(args); if (ex != null) { ex.printStackTrace(); } watch.stop(); log.info("Elapsed time: " + watch.getTime() / 1000 + " seconds"); } catch (Exception e) { throw new RuntimeException(e); } System.exit(0); }
From source file:edu.jhu.hlt.concrete.gigaword.expt.ConvertGigawordDocuments.java
/** * @param args//from w w w .j a v a 2 s .c om */ public static void main(String... args) { Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { logger.error("Thread {} caught unhandled exception.", t.getName()); logger.error("Unhandled exception.", e); } }); if (args.length != 2) { logger.info("Usage: {} {} {}", GigawordConcreteConverter.class.getName(), "path/to/expt/file", "path/to/out/folder"); System.exit(1); } String exptPathStr = args[0]; String outPathStr = args[1]; // Verify path points to something. Path exptPath = Paths.get(exptPathStr); if (!Files.exists(exptPath)) { logger.error("File: {} does not exist. Re-run with the correct path to " + " the experiment 2 column file. See README.md."); System.exit(1); } logger.info("Experiment map located at: {}", exptPathStr); // Create output dir if not yet created. Path outPath = Paths.get(outPathStr); if (!Files.exists(outPath)) { logger.info("Creating directory: {}", outPath.toString()); try { Files.createDirectories(outPath); } catch (IOException e) { logger.error("Caught an IOException when creating output dir.", e); System.exit(1); } } logger.info("Output directory located at: {}", outPathStr); // Read in expt map. See README.md. Map<String, Set<String>> exptMap = null; try (Reader r = ExperimentUtils.createReader(exptPath); BufferedReader br = new BufferedReader(r)) { exptMap = ExperimentUtils.createFilenameToIdMap(br); } catch (IOException e) { logger.error("Caught an IOException when creating expt map.", e); System.exit(1); } // Start a timer. logger.info("Gigaword -> Concrete beginning."); StopWatch sw = new StopWatch(); sw.start(); // Iterate over expt map. exptMap.entrySet() // .parallelStream() .forEach(p -> { final String pathStr = p.getKey(); final Set<String> ids = p.getValue(); final Path lp = Paths.get(pathStr); logger.info("Converting path: {}", pathStr); // Get the file name and immediate folder it is under. int nElements = lp.getNameCount(); Path fileName = lp.getName(nElements - 1); Path subFolder = lp.getName(nElements - 2); String newFnStr = fileName.toString().split("\\.")[0] + ".tar"; // Mirror folders in output dir. Path localOutFolder = outPath.resolve(subFolder); Path localOutPath = localOutFolder.resolve(newFnStr); // Create output subfolders. if (!Files.exists(localOutFolder) && !Files.isDirectory(localOutFolder)) { logger.info("Creating out file: {}", localOutFolder.toString()); try { Files.createDirectories(localOutFolder); } catch (IOException e) { throw new RuntimeException("Caught an IOException when creating output dir.", e); } } // Iterate over communications. Iterator<Communication> citer; try (OutputStream os = Files.newOutputStream(localOutPath); BufferedOutputStream bos = new BufferedOutputStream(os); Archiver archiver = new TarArchiver(bos);) { citer = new ConcreteGigawordDocumentFactory().iterator(lp); while (citer.hasNext()) { Communication c = citer.next(); String cId = c.getId(); // Document ID must be in the set. Remove. boolean wasInSet = ids.remove(cId); if (!wasInSet) { // Some IDs are duplicated in Gigaword. // See ERRATA. logger.debug( "ID: {} was parsed from path: {}, but was not in the experiment map. Attempting to remove dupe.", cId, pathStr); // Attempt to create a duplicate id (append .duplicate to the id). // Then, try to remove again. String newId = RepairDuplicateIDs.repairDuplicate(cId); boolean dupeRemoved = ids.remove(newId); // There are not nested duplicates, so this should never fire. if (!dupeRemoved) { logger.info("Failed to remove dupe."); return; } else // Modify the communication ID to the unique version. c.setId(newId); } archiver.addEntry(new ArchivableCommunication(c)); } logger.info("Finished path: {}", pathStr); } catch (ConcreteException ex) { logger.error("Caught ConcreteException during Concrete mapping.", ex); logger.error("Path: {}", pathStr); } catch (IOException e) { logger.error("Error archiving communications.", e); logger.error("Path: {}", localOutPath.toString()); } }); sw.stop(); logger.info("Finished."); Minutes m = new Duration(sw.getTime()).toStandardMinutes(); logger.info("Runtime: Approximately {} minutes.", m.getMinutes()); }
From source file:chibi.gemmaanalysis.CorrelationAnalysisCLI.java
public static void main(String[] args) { CorrelationAnalysisCLI analysis = new CorrelationAnalysisCLI(); StopWatch watch = new StopWatch(); watch.start();/* www .jav a 2 s . c o m*/ log.info("Starting Correlation Analysis"); Exception exc = analysis.doWork(args); if (exc != null) { log.error(exc.getMessage()); } log.info("Finished analysis in " + watch); }
From source file:jsdp.app.control.clqg.univariate.CLQG.java
public static void main(String args[]) { /******************************************************************* * Problem parameters// w w w . j a va 2 s.co m */ int T = 20; // Horizon length double G = 1; // Input transition double Phi = 1; // State transition double R = 1; // Input cost double Q = 1; // State cost double Ulb = -1; // Action constraint double Uub = 20; // Action constraint double noiseStd = 5; // Standard deviation of the noise double[] noiseStdArray = new double[T]; Arrays.fill(noiseStdArray, noiseStd); double truncationQuantile = 0.975; // Random variables Distribution[] distributions = IntStream.iterate(0, i -> i + 1).limit(noiseStdArray.length) .mapToObj(i -> new NormalDist(0, noiseStdArray[i])) .toArray(Distribution[]::new); double[] supportLB = IntStream.iterate(0, i -> i + 1).limit(T) .mapToDouble(i -> NormalDist.inverseF(0, noiseStdArray[i], 1 - truncationQuantile)).toArray(); double[] supportUB = IntStream.iterate(0, i -> i + 1).limit(T) .mapToDouble(i -> NormalDist.inverseF(0, noiseStdArray[i], truncationQuantile)).toArray(); double initialX = 0; // Initial state /******************************************************************* * Model definition */ // State space double stepSize = 0.5; //Stepsize must be 1 for discrete distributions double minState = -25; double maxState = 100; StateImpl.setStateBoundaries(stepSize, minState, maxState); // Actions Function<State, ArrayList<Action>> buildActionList = (Function<State, ArrayList<Action>> & Serializable) s -> { StateImpl state = (StateImpl) s; ArrayList<Action> feasibleActions = new ArrayList<Action>(); double maxAction = Math.min(Uub, (StateImpl.getMaxState() - Phi * state.getInitialState()) / G); double minAction = Math.max(Ulb, (StateImpl.getMinState() - Phi * state.getInitialState()) / G); for (double actionPointer = minAction; actionPointer <= maxAction; actionPointer += StateImpl .getStepSize()) { feasibleActions.add(new ActionImpl(state, actionPointer)); } return feasibleActions; }; Function<State, Action> idempotentAction = (Function<State, Action> & Serializable) s -> new ActionImpl(s, 0.0); ImmediateValueFunction<State, Action, Double> immediateValueFunction = (initialState, action, finalState) -> { ActionImpl a = (ActionImpl) action; StateImpl fs = (StateImpl) finalState; double inputCost = Math.pow(a.getAction(), 2) * R; double stateCost = Math.pow(fs.getInitialState(), 2) * Q; return inputCost + stateCost; }; // Random Outcome Function RandomOutcomeFunction<State, Action, Double> randomOutcomeFunction = (initialState, action, finalState) -> { double realizedNoise = ((StateImpl) finalState).getInitialState() - ((StateImpl) initialState).getInitialState() * Phi - ((ActionImpl) action).getAction() * G; return realizedNoise; }; /******************************************************************* * Solve */ // Sampling scheme SamplingScheme samplingScheme = SamplingScheme.NONE; int maxSampleSize = 50; double reductionFactorPerStage = 1; // Value Function Processing Method: backward recursion double discountFactor = 1.0; int stateSpaceLowerBound = 10000000; float loadFactor = 0.8F; BackwardRecursionImpl recursion = new BackwardRecursionImpl(OptimisationDirection.MIN, distributions, supportLB, supportUB, immediateValueFunction, randomOutcomeFunction, buildActionList, idempotentAction, discountFactor, samplingScheme, maxSampleSize, reductionFactorPerStage, stateSpaceLowerBound, loadFactor, HashType.THASHMAP); System.out.println("--------------Backward recursion--------------"); StopWatch timer = new StopWatch(); OperatingSystemMXBean osMBean; try { osMBean = ManagementFactory.newPlatformMXBeanProxy(ManagementFactory.getPlatformMBeanServer(), ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class); long nanoBefore = System.nanoTime(); long cpuBefore = osMBean.getProcessCpuTime(); timer.start(); recursion.runBackwardRecursionMonitoring(); timer.stop(); long cpuAfter = osMBean.getProcessCpuTime(); long nanoAfter = System.nanoTime(); long percent; if (nanoAfter > nanoBefore) percent = ((cpuAfter - cpuBefore) * 100L) / (nanoAfter - nanoBefore); else percent = 0; System.out.println( "Cpu usage: " + percent + "% (" + Runtime.getRuntime().availableProcessors() + " cores)"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(); double ETC = recursion.getExpectedCost(initialX); StateDescriptorImpl initialState = new StateDescriptorImpl(0, initialX); double action = recursion.getOptimalAction(initialState).getAction(); System.out.println("Expected total cost (assuming an initial state " + initialX + "): " + ETC); System.out.println("Optimal initial action: " + action); System.out.println("Time elapsed: " + timer); System.out.println(); }
From source file:chibi.gemmaanalysis.MetaLinkFinderCli.java
/** * @param args//w w w . j a v a2 s . com */ public static void main(String[] args) { MetaLinkFinderCli linkFinderCli = new MetaLinkFinderCli(); StopWatch watch = new StopWatch(); watch.start(); try { Exception ex = linkFinderCli.doWork(args); if (ex != null) { ex.printStackTrace(); } watch.stop(); log.info(watch.getTime()); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.mgmtp.jfunk.core.JFunk.java
/** * Starts jFunk./*www .j a v a2s .co m*/ * * <pre> * -threadcount=<count> Optional Number of threads to be used. Allows for parallel * execution of test scripts. * -parallel Optional Allows a single script to be executed in parallel * depending on the number of threads specified. The * argument is ignored if multiple scripts are specified. * <script parameters> Optional Similar to Java system properties they can be provided * as key-value-pairs preceded by -S, e.g. -Skey=value. * These parameters are then available in the script as * Groovy variables. * <script(s)> Required At least one test script must be specified. * * Example: * java -cp <jFunkClasspath> com.mgmtp.jfunk.core.JFunk -Skey=value -threadcount=4 -parallel mytest.script * </pre> * * @param args * The program arguments. */ public static void main(final String[] args) { SLF4JBridgeHandler.install(); boolean exitWithError = true; StopWatch stopWatch = new StopWatch(); try { RESULT_LOG.info("jFunk started"); stopWatch.start(); int threadCount = 1; boolean parallel = false; Properties scriptProperties = new Properties(); List<File> scripts = Lists.newArrayList(); for (String arg : args) { if (arg.startsWith("-threadcount")) { String[] split = arg.split("="); Preconditions.checkArgument(split.length == 2, "The number of threads must be specified as follows: -threadcount=<value>"); threadCount = Integer.parseInt(split[1]); RESULT_LOG.info("Using " + threadCount + (threadCount == 1 ? " thread" : " threads")); } else if (arg.startsWith("-S")) { arg = arg.substring(2); String[] split = arg.split("="); Preconditions.checkArgument(split.length == 2, "Script parameters must be given in the form -S<name>=<value>"); scriptProperties.setProperty(split[0], normalizeScriptParameterValue(split[1])); RESULT_LOG.info("Using script parameter " + split[0] + " with value " + split[1]); } else if (arg.equals("-parallel")) { parallel = true; RESULT_LOG.info("Using parallel mode"); } else { scripts.add(new File(arg)); } } if (scripts.isEmpty()) { scripts.addAll(requestScriptsViaGui()); if (scripts.isEmpty()) { RESULT_LOG.info("Execution finished (took " + stopWatch + " H:mm:ss.SSS)"); System.exit(0); } } String propsFileName = System.getProperty("jfunk.props.file", "jfunk.properties"); Module module = ModulesLoader.loadModulesFromProperties(new JFunkDefaultModule(), propsFileName); Injector injector = Guice.createInjector(module); JFunkFactory factory = injector.getInstance(JFunkFactory.class); JFunkBase jFunk = factory.create(threadCount, parallel, scripts, scriptProperties); jFunk.execute(); exitWithError = false; } catch (JFunkExecutionException ex) { // no logging necessary } catch (Exception ex) { Logger.getLogger(JFunk.class).error("jFunk terminated unexpectedly.", ex); } finally { stopWatch.stop(); RESULT_LOG.info("Execution finished (took " + stopWatch + " H:mm:ss.SSS)"); } System.exit(exitWithError ? -1 : 0); }