List of usage examples for java.util.concurrent TimeUnit MILLISECONDS
TimeUnit MILLISECONDS
To view the source code for java.util.concurrent TimeUnit MILLISECONDS.
Click Source Link
From source file:com.mmounirou.spotirss.SpotiRss.java
/** * @param args// w w w .j ava 2 s . com * @throws IOException * @throws ClassNotFoundException * @throws IllegalAccessException * @throws InstantiationException * @throws SpotifyClientException * @throws ChartRssException * @throws SpotifyException */ public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, SpotifyClientException { if (args.length == 0) { System.err.println("usage : java -jar spotiboard.jar <charts-folder>"); return; } Properties connProperties = new Properties(); InputStream inStream = SpotiRss.class.getResourceAsStream("/spotify-server.properties"); try { connProperties.load(inStream); } finally { IOUtils.closeQuietly(inStream); } String host = connProperties.getProperty("host"); int port = Integer.parseInt(connProperties.getProperty("port")); String user = connProperties.getProperty("user"); final SpotifyClient spotifyClient = new SpotifyClient(host, port, user); final Map<String, Playlist> playlistsByTitle = getPlaylistsByTitle(spotifyClient); final File outputDir = new File(args[0]); outputDir.mkdirs(); TrackCache cache = new TrackCache(); try { for (String strProvider : PROVIDERS) { String providerClassName = EntryToTrackConverter.class.getPackage().getName() + "." + StringUtils.capitalize(strProvider); final EntryToTrackConverter converter = (EntryToTrackConverter) SpotiRss.class.getClassLoader() .loadClass(providerClassName).newInstance(); Iterable<String> chartsRss = getCharts(strProvider); final File resultDir = new File(outputDir, strProvider); resultDir.mkdir(); final SpotifyHrefQuery hrefQuery = new SpotifyHrefQuery(cache); Iterable<String> results = FluentIterable.from(chartsRss).transform(new Function<String, String>() { @Override @Nullable public String apply(@Nullable String chartRss) { try { long begin = System.currentTimeMillis(); ChartRss bilboardChartRss = ChartRss.getInstance(chartRss, converter); Map<Track, String> trackHrefs = hrefQuery.getTrackHrefs(bilboardChartRss.getSongs()); String strTitle = bilboardChartRss.getTitle(); File resultFile = new File(resultDir, strTitle); List<String> lines = Lists.newLinkedList(FluentIterable.from(trackHrefs.keySet()) .transform(Functions.toStringFunction())); lines.addAll(trackHrefs.values()); FileUtils.writeLines(resultFile, Charsets.UTF_8.displayName(), lines); Playlist playlist = playlistsByTitle.get(strTitle); if (playlist != null) { playlist.getTracks().clear(); playlist.getTracks().addAll(trackHrefs.values()); spotifyClient.patch(playlist); LOGGER.info(String.format("%s chart exported patched", strTitle)); } LOGGER.info(String.format("%s chart exported in %s in %d s", strTitle, resultFile.getAbsolutePath(), (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - begin))); } catch (Exception e) { LOGGER.error(String.format("fail to export %s charts", chartRss), e); } return ""; } }); // consume iterables Iterables.size(results); } } finally { cache.close(); } }
From source file:com.couchbase.roadrunner.RoadRunner.java
/** * Initialize the RoadRunner./*from w ww . ja v a 2 s . c om*/ * * This method is responsible for parsing the passed in command line arguments * and also dispatch the bootstrapping of the actual workload runner. * * @param args Command line arguments to be passed in. */ public static void main(final String[] args) { CommandLine params = null; try { params = parseCommandLine(args); } catch (ParseException ex) { LOGGER.error("Exception while parsing command line!", ex); System.exit(-1); } if (params.hasOption(OPT_HELP)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("roadrunner", getCommandLineOptions()); System.exit(0); } GlobalConfig config = GlobalConfig.fromCommandLine(params); WorkloadDispatcher dispatcher = new WorkloadDispatcher(config); LOGGER.info("Running with Config: " + config.toString()); try { LOGGER.debug("Initializing ClientHandlers."); dispatcher.init(); } catch (Exception ex) { LOGGER.error("Error while initializing the ClientHandlers: ", ex); System.exit(-1); } Stopwatch workloadStopwatch = new Stopwatch().start(); try { LOGGER.info("Running Workload."); dispatcher.dispatchWorkload(); } catch (Exception ex) { LOGGER.error("Error while running the Workload: ", ex); System.exit(-1); } workloadStopwatch.stop(); LOGGER.debug("Finished Workload."); LOGGER.info("==== RESULTS ===="); dispatcher.prepareMeasures(); long totalOps = dispatcher.getTotalOps(); long measuredOps = dispatcher.getMeasuredOps(); LOGGER.info("Operations: measured " + measuredOps + "ops out of total " + totalOps + "ops."); Map<String, List<Stopwatch>> measures = dispatcher.getMeasures(); for (Map.Entry<String, List<Stopwatch>> entry : measures.entrySet()) { Histogram h = new Histogram(60 * 60 * 1000, 5); for (Stopwatch watch : entry.getValue()) { h.recordValue(watch.elapsed(TimeUnit.MICROSECONDS)); } LOGGER.info("Percentile (microseconds) for \"" + entry.getKey() + "\" Workload:"); LOGGER.info(" 50%:" + (Math.round(h.getValueAtPercentile(0.5) * 100) / 100) + " 75%:" + (Math.round(h.getValueAtPercentile(0.75) * 100) / 100) + " 95%:" + (Math.round(h.getValueAtPercentile(0.95) * 100) / 100) + " 99%:" + (Math.round(h.getValueAtPercentile(0.99) * 100) / 100)); } LOGGER.info("Elapsed: " + workloadStopwatch.elapsed(TimeUnit.MILLISECONDS) + "ms"); List<Stopwatch> elapsedThreads = dispatcher.getThreadElapsed(); long shortestThread = 0; long longestThread = 0; for (Stopwatch threadWatch : elapsedThreads) { long threadMs = threadWatch.elapsed(TimeUnit.MILLISECONDS); if (longestThread == 0 || threadMs > longestThread) { longestThread = threadMs; } if (shortestThread == 0 || threadMs < shortestThread) { shortestThread = threadMs; } } LOGGER.info("Shortest Thread: " + shortestThread + "ms"); LOGGER.info("Longest Thread: " + longestThread + "ms"); }
From source file:general.Main.java
/** * Selects the files to be processed and specifies the files to write to. * * @param args Arguments to specify runtime behavior. */// w ww . j a v a 2 s .co m public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { Options options = new Options(); options.addOption("l", "logging", false, "enables file logging"); options.addOption("j", "jena", false, "uses the Jena SPARQL Parser"); options.addOption("o", "openrdf", false, "uses the OpenRDF SPARQL Parser"); options.addOption("f", "file", true, "defines the input file prefix"); options.addOption("h", "help", false, "displays this help"); options.addOption("t", "tsv", false, "reads from .tsv-files"); // options.addOption("p", "parquet", false, "read from .parquet-files"); options.addOption("n", "numberOfThreads", true, "number of used threads, default 1"); options.addOption("b", "withBots", false, "enables metric calculation for bot queries+"); options.addOption("p", "readPreprocessed", false, "enables reading of preprocessed files"); //some parameters which can be changed through parameters //QueryHandler queryHandler = new OpenRDFQueryHandler(); String inputFilePrefix; String inputFileSuffix = ".tsv"; String queryParserName = "OpenRDF"; Class inputHandlerClass = null; Class queryHandlerClass = null; int numberOfThreads = 1; CommandLineParser parser = new DefaultParser(); CommandLine cmd; try { cmd = parser.parse(options, args); if (cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("help", options); return; } if (cmd.hasOption("openrdf")) { queryHandlerClass = OpenRDFQueryHandler.class; } if (cmd.hasOption("tsv")) { inputFileSuffix = ".tsv"; inputHandlerClass = InputHandlerTSV.class; } if (cmd.hasOption("parquet")) { inputFileSuffix = ".parquet"; Logger.getLogger("org").setLevel(Level.WARN); Logger.getLogger("akka").setLevel(Level.WARN); SparkConf conf = new SparkConf().setAppName("SPARQLQueryAnalyzer").setMaster("local"); JavaSparkContext sc = new JavaSparkContext(conf); inputHandlerClass = InputHandlerParquet.class; } if (inputHandlerClass == null) { System.out.println("Please specify which parser to use, either -t for TSV or -p for parquet."); } if (cmd.hasOption("file")) { inputFilePrefix = cmd.getOptionValue("file").trim(); } else { System.out.println( "Please specify at least the file which we should work on using the option '--file PREFIX' or 'f PREFIX'"); return; } if (cmd.hasOption("logging")) { LoggingHandler.initFileLog(queryParserName, inputFilePrefix); } if (cmd.hasOption("numberOfThreads")) { numberOfThreads = Integer.parseInt(cmd.getOptionValue("numberOfThreads")); } if (cmd.hasOption("withBots")) { withBots = true; } if (cmd.hasOption("readPreprocessed")) { readPreprocessed = true; } } catch (UnrecognizedOptionException e) { System.out.println("Unrecognized commandline option: " + e.getOption()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("help", options); return; } catch (ParseException e) { System.out.println( "There was an error while parsing your command line input. Did you rechecked your syntax before running?"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("help", options); return; } LoggingHandler.initConsoleLog(); loadPreBuildQueryTypes(); long startTime = System.nanoTime(); ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads); for (int day = 1; day <= 31; day++) { String inputFile = inputFilePrefix + String.format("%02d", day) + inputFileSuffix; Runnable parseOneMonthWorker = new ParseOneMonthWorker(inputFile, inputFilePrefix, inputHandlerClass, queryParserName, queryHandlerClass, day); executor.execute(parseOneMonthWorker); } executor.shutdown(); while (!executor.isTerminated()) { //wait until all workers are finished } writeQueryTypes(inputFilePrefix); long stopTime = System.nanoTime(); long millis = TimeUnit.MILLISECONDS.convert(stopTime - startTime, TimeUnit.NANOSECONDS); Date date = new Date(millis); System.out.println("Finished executing with all threads: " + new SimpleDateFormat("mm-dd HH:mm:ss:SSSSSSS").format(date)); }
From source file:DIA_Umpire_Quant.DIA_Umpire_LCMSIDGen.java
/** * @param args the command line arguments *//* w w w. jav a 2 s . c o m*/ public static void main(String[] args) throws FileNotFoundException, IOException, Exception { System.out.println( "================================================================================================="); System.out.println("DIA-Umpire LCMSID geneartor (version: " + UmpireInfo.GetInstance().Version + ")"); if (args.length != 1) { System.out.println( "command format error, the correct format should be: java -jar -Xmx10G DIA_Umpire_LCMSIDGen.jar diaumpire_module.params"); return; } try { ConsoleLogger.SetConsoleLogger(Level.INFO); ConsoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "diaumpire_lcmsidgen.log"); } catch (Exception e) { } Logger.getRootLogger().info("Version: " + UmpireInfo.GetInstance().Version); Logger.getRootLogger().info("Parameter file:" + args[0]); BufferedReader reader = new BufferedReader(new FileReader(args[0])); String line = ""; String WorkFolder = ""; int NoCPUs = 2; TandemParam tandemPara = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600); HashMap<String, File> AssignFiles = new HashMap<>(); //<editor-fold defaultstate="collapsed" desc="Reading parameter file"> while ((line = reader.readLine()) != null) { line = line.trim(); Logger.getRootLogger().info(line); if (!"".equals(line) && !line.startsWith("#")) { //System.out.println(line); if (line.equals("==File list begin")) { do { line = reader.readLine(); line = line.trim(); if (line.equals("==File list end")) { continue; } else if (!"".equals(line)) { File newfile = new File(line); if (newfile.exists()) { AssignFiles.put(newfile.getAbsolutePath(), newfile); } else { Logger.getRootLogger().info("File: " + newfile + " does not exist."); } } } while (!line.equals("==File list end")); } if (line.split("=").length < 2) { continue; } String type = line.split("=")[0].trim(); String value = line.split("=")[1].trim(); switch (type) { case "Path": { WorkFolder = value; break; } case "path": { WorkFolder = value; break; } case "Thread": { NoCPUs = Integer.parseInt(value); break; } case "DecoyPrefix": { if (!"".equals(value)) { tandemPara.DecoyPrefix = value; } break; } case "PeptideFDR": { tandemPara.PepFDR = Float.parseFloat(value); break; } } } } //</editor-fold> //Initialize PTM manager using compomics library PTMManager.GetInstance(); //Generate DIA file list ArrayList<DIAPack> FileList = new ArrayList<>(); File folder = new File(WorkFolder); if (!folder.exists()) { Logger.getRootLogger().info("The path : " + WorkFolder + " cannot be found."); System.exit(1); } for (final File fileEntry : folder.listFiles()) { if (fileEntry.isFile() && (fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml") | fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzml")) && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml") && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml") && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) { AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry); } if (fileEntry.isDirectory()) { for (final File fileEntry2 : fileEntry.listFiles()) { if (fileEntry2.isFile() && (fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml") | fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzml")) && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml") && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml") && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) { AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2); } } } } Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size()); for (File fileEntry : AssignFiles.values()) { Logger.getRootLogger().info(fileEntry.getAbsolutePath()); } //process each DIA file to genearate untargeted identifications for (File fileEntry : AssignFiles.values()) { String mzXMLFile = fileEntry.getAbsolutePath(); if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) { long time = System.currentTimeMillis(); DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs); FileList.add(DiaFile); Logger.getRootLogger().info( "================================================================================================="); Logger.getRootLogger().info("Processing " + mzXMLFile); if (!DiaFile.LoadDIASetting()) { Logger.getRootLogger().info("Loading DIA setting failed, job is incomplete"); System.exit(1); } if (!DiaFile.LoadParams()) { Logger.getRootLogger().info("Loading parameters failed, job is incomplete"); System.exit(1); } Logger.getRootLogger().info("Loading identification results " + mzXMLFile + "...."); DiaFile.ParsePepXML(tandemPara, null); DiaFile.BuildStructure(); if (!DiaFile.MS1FeatureMap.ReadPeakCluster()) { Logger.getRootLogger().info("Loading peak and structure failed, job is incomplete"); System.exit(1); } DiaFile.MS1FeatureMap.ClearMonoisotopicPeakOfCluster(); //Generate mapping between index of precursor feature and pseudo MS/MS scan index DiaFile.GenerateClusterScanNomapping(); //Doing quantification DiaFile.AssignQuant(); DiaFile.ClearStructure(); DiaFile.IDsummary.ReduceMemoryUsage(); time = System.currentTimeMillis() - time; Logger.getRootLogger().info(mzXMLFile + " processed time:" + String.format("%d hour, %d min, %d sec", TimeUnit.MILLISECONDS.toHours(time), TimeUnit.MILLISECONDS.toMinutes(time) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time)), TimeUnit.MILLISECONDS.toSeconds(time) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time)))); } Logger.getRootLogger().info("Job done"); Logger.getRootLogger().info( "================================================================================================="); } }
From source file:Main.java
public static int expireTimeInDays(long time) { return (int) TimeUnit.MILLISECONDS.toDays(time - System.currentTimeMillis()); }
From source file:Main.java
public static void pause(long timeMillis) { try {//from w w w . ja v a2 s .co m TimeUnit.MILLISECONDS.sleep(timeMillis); } catch (InterruptedException e) { throw new RuntimeException("Interrupted in pause !"); } }
From source file:Main.java
public static final void sleep4MilliSec(long timeout) { sleep(TimeUnit.MILLISECONDS, timeout); }
From source file:Main.java
public static void delay(int milliseconds) { try {/* w ww . j a v a 2 s .co m*/ TimeUnit.MILLISECONDS.sleep(milliseconds); } catch (InterruptedException e) { throw new IllegalStateException(e); } }
From source file:Main.java
public static long millitime() { return TimeUnit.MILLISECONDS.convert(System.nanoTime(), TimeUnit.NANOSECONDS); }
From source file:Main.java
public static String timeFormatMillis(int millis) { long seconds = TimeUnit.MILLISECONDS.toSeconds(millis); long minutes = seconds / 60; seconds = seconds - minutes * 60;//www.j a va 2s. co m return String.format("%01d:%02d", minutes, seconds); }