List of usage examples for java.lang System currentTimeMillis
@HotSpotIntrinsicCandidate public static native long currentTimeMillis();
From source file:com.damon.rocketmq.example.benchmark.Producer.java
public static void main(String[] args) throws MQClientException, UnsupportedEncodingException { Options options = ServerUtil.buildCommandlineOptions(new Options()); CommandLine commandLine = ServerUtil.parseCmdLine("benchmarkProducer", args, buildCommandlineOptions(options), new PosixParser()); if (null == commandLine) { System.exit(-1);//w ww.j av a 2s. c o m } final String topic = commandLine.hasOption('t') ? commandLine.getOptionValue('t').trim() : "BenchmarkTest"; final int threadCount = commandLine.hasOption('w') ? Integer.parseInt(commandLine.getOptionValue('w')) : 64; final int messageSize = commandLine.hasOption('s') ? Integer.parseInt(commandLine.getOptionValue('s')) : 128; final boolean keyEnable = commandLine.hasOption('k') && Boolean.parseBoolean(commandLine.getOptionValue('k')); System.out.printf("topic %s threadCount %d messageSize %d keyEnable %s%n", topic, threadCount, messageSize, keyEnable); final Logger log = ClientLogger.getLog(); final Message msg = buildMessage(messageSize, topic); final ExecutorService sendThreadPool = Executors.newFixedThreadPool(threadCount); final StatsBenchmarkProducer statsBenchmark = new StatsBenchmarkProducer(); final Timer timer = new Timer("BenchmarkTimerThread", true); final LinkedList<Long[]> snapshotList = new LinkedList<Long[]>(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { snapshotList.addLast(statsBenchmark.createSnapshot()); if (snapshotList.size() > 10) { snapshotList.removeFirst(); } } }, 1000, 1000); timer.scheduleAtFixedRate(new TimerTask() { private void printStats() { if (snapshotList.size() >= 10) { Long[] begin = snapshotList.getFirst(); Long[] end = snapshotList.getLast(); final long sendTps = (long) (((end[3] - begin[3]) / (double) (end[0] - begin[0])) * 1000L); final double averageRT = (end[5] - begin[5]) / (double) (end[3] - begin[3]); System.out.printf( "Send TPS: %d Max RT: %d Average RT: %7.3f Send Failed: %d Response Failed: %d%n", sendTps, statsBenchmark.getSendMessageMaxRT().get(), averageRT, end[2], end[4]); } } @Override public void run() { try { this.printStats(); } catch (Exception e) { e.printStackTrace(); } } }, 10000, 10000); final DefaultMQProducer producer = new DefaultMQProducer("benchmark_producer"); producer.setInstanceName(Long.toString(System.currentTimeMillis())); if (commandLine.hasOption('n')) { String ns = commandLine.getOptionValue('n'); producer.setNamesrvAddr(ns); } producer.setCompressMsgBodyOverHowmuch(Integer.MAX_VALUE); producer.start(); for (int i = 0; i < threadCount; i++) { sendThreadPool.execute(new Runnable() { @Override public void run() { while (true) { try { final long beginTimestamp = System.currentTimeMillis(); if (keyEnable) { msg.setKeys(String.valueOf(beginTimestamp / 1000)); } producer.send(msg); statsBenchmark.getSendRequestSuccessCount().incrementAndGet(); statsBenchmark.getReceiveResponseSuccessCount().incrementAndGet(); final long currentRT = System.currentTimeMillis() - beginTimestamp; statsBenchmark.getSendMessageSuccessTimeTotal().addAndGet(currentRT); long prevMaxRT = statsBenchmark.getSendMessageMaxRT().get(); while (currentRT > prevMaxRT) { boolean updated = statsBenchmark.getSendMessageMaxRT().compareAndSet(prevMaxRT, currentRT); if (updated) break; prevMaxRT = statsBenchmark.getSendMessageMaxRT().get(); } } catch (RemotingException e) { statsBenchmark.getSendRequestFailedCount().incrementAndGet(); log.error("[BENCHMARK_PRODUCER] Send Exception", e); try { Thread.sleep(3000); } catch (InterruptedException ignored) { } } catch (InterruptedException e) { statsBenchmark.getSendRequestFailedCount().incrementAndGet(); try { Thread.sleep(3000); } catch (InterruptedException e1) { } } catch (MQClientException e) { statsBenchmark.getSendRequestFailedCount().incrementAndGet(); log.error("[BENCHMARK_PRODUCER] Send Exception", e); } catch (MQBrokerException e) { statsBenchmark.getReceiveResponseFailedCount().incrementAndGet(); log.error("[BENCHMARK_PRODUCER] Send Exception", e); try { Thread.sleep(3000); } catch (InterruptedException ignored) { } } } } }); } }
From source file:autocorrelator.apps.SDFGroovy.java
public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); // create command line Options object Options options = new Options(); Option opt = new Option("in", true, "input sd file"); options.addOption(opt);//from w ww .j a va 2 s. c o m opt = new Option("out", true, "output file for return value true or null"); options.addOption(opt); opt = new Option("falseOut", true, "output file for return value false"); options.addOption(opt); opt = new Option("c", true, "groovy script line"); options.addOption(opt); opt = new Option("f", true, "groovy script file"); options.addOption(opt); opt = new Option("exception", true, "exception handling (Default: stop)"); options.addOption(opt); opt = new Option("h", false, "print help message"); options.addOption(opt); CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (Exception e) { exitWithHelp(e.getMessage(), options); } if (!cmd.hasOption("c") && !cmd.hasOption("f")) exitWithHelp("-c or -f must be given!", options); if (cmd.hasOption("c") && cmd.hasOption("f")) exitWithHelp("Only one of -c or -f may be given!", options); String groovyStrg; if (cmd.hasOption("c")) groovyStrg = cmd.getOptionValue("c"); else groovyStrg = fileToString(cmd.getOptionValue("f")); Set<String> inFileds = new HashSet<String>(); Set<String> outFields = new HashSet<String>(); Script script = getGroovyScript(groovyStrg, inFileds, outFields); if (cmd.hasOption("h")) { callScriptHelp(script); exitWithHelp("", options); } if (!cmd.hasOption("in") || !cmd.hasOption("out")) { callScriptHelp(script); exitWithHelp("-in and -out must be given", options); } String[] scriptArgs = cmd.getArgs(); String inFile = cmd.getOptionValue("in"); String outFile = cmd.getOptionValue("out"); String falseOutFile = cmd.getOptionValue("falseOut"); EXCEPTIONHandling eHandling = EXCEPTIONHandling.stop; if (cmd.hasOption("exception")) eHandling = EXCEPTIONHandling.getByName(cmd.getOptionValue("exception")); callScriptInit(script, scriptArgs); oemolistream ifs = new oemolistream(inFile); oemolostream ofs = new oemolostream(outFile); oemolostream falseOFS = null; if (falseOutFile != null) falseOFS = new oemolostream(falseOutFile); OEMolBase mol = new OEGraphMol(); int iCounter = 0; int oCounter = 0; int foCounter = 0; while (oechem.OEReadMolecule(ifs, mol)) { iCounter++; Binding binding = getFieldBindings(mol, inFileds, outFields); script.setBinding(binding); boolean printToTrue = true; boolean printToFalse = true; try { Object ret = script.run(); if (ret == null || !(ret instanceof Boolean)) { printToFalse = false; } else if (((Boolean) ret).booleanValue()) { printToFalse = false; } else // ret = false { printToTrue = false; } setOutputFields(mol, binding, outFields); } catch (Exception e) { switch (eHandling) { case stop: throw e; case printToTrue: printToFalse = false; System.err.println(e.getMessage()); break; case printToFalse: printToTrue = false; System.err.println(e.getMessage()); break; case dropRecord: printToTrue = false; printToFalse = false; System.err.println(e.getMessage()); break; default: assert false; break; } } if (printToTrue) { oechem.OEWriteMolecule(ofs, mol); oCounter++; } if (falseOFS != null && printToFalse) { oechem.OEWriteMolecule(falseOFS, mol); foCounter++; } } System.err.printf("SDFGroovy: Input %d, output %d,%d structures in %dsec\n", iCounter, oCounter, foCounter, (System.currentTimeMillis() - start) / 1000); if (falseOFS != null) falseOFS.close(); ofs.close(); ifs.close(); mol.delete(); }
From source file:org.jfree.chart.demo.PerformanceTest1.java
public static void main(String args[]) { ArrayList<Double> arraylist = new ArrayList<Double>(); for (int i = 0; i < 4000; i++) arraylist.add(new Double(Math.random())); int j = 0;//from w w w. j av a2s .c o m for (int k = 0; k < 20000; k++) { long l = System.currentTimeMillis(); for (int i1 = 0; i1 < 0xf4240; i1++) j += i1; long l1 = System.currentTimeMillis(); System.out.println(k + " --> " + (l1 - l) + " (" + Runtime.getRuntime().freeMemory() + " / " + Runtime.getRuntime().totalMemory() + ")"); } }
From source file:de.urszeidler.ethereum.licencemanager1.deployer.LicenseManagerDeployer.java
/** * @param args/* www.j a v a2 s .com*/ */ public static void main(String[] args) { Options options = createOptions(); CommandLineParser parser = new DefaultParser(); int returnValue = 0; boolean dontExit = false; try { CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption("h")) { printHelp(options); return; } if (commandLine.hasOption("de")) dontExit = true; String senderKey = null; String senderPass = null; if (commandLine.hasOption("sk")) senderKey = commandLine.getOptionValue("sk"); if (commandLine.hasOption("sp")) senderPass = commandLine.getOptionValue("sp"); LicenseManagerDeployer manager = new LicenseManagerDeployer(); try { manager.init(senderKey, senderPass); long currentMili = 0; EthValue balance = null; if (commandLine.hasOption("calcDeploymendCost")) { currentMili = System.currentTimeMillis(); balance = manager.ethereum.getBalance(manager.sender); } if (commandLine.hasOption("observeBlock")) { manager.ethereum.events().observeBlocks() .subscribe(b -> System.out.println("Block: " + b.blockNumber + " " + b.receipts)); } if (commandLine.hasOption("f")) { String[] values = commandLine.getOptionValues("f"); String filename = values[0]; String isCompiled = values[1]; manager.deployer.setContractSource(filename, Boolean.parseBoolean(isCompiled)); } if (commandLine.hasOption("millis")) { manager.setMillis(Long.parseLong(commandLine.getOptionValue("millis"))); } if (commandLine.hasOption("c")) { String[] values = commandLine.getOptionValues("c"); if (values == null || values.length != 2) { System.out.println("Error. Need 2 parameters: paymentAddress,name"); System.out.println(""); printHelp(options); return; } String paymentAddress = values[0]; String name = values[1]; manager.deployLicenseManager(EthAddress.of(paymentAddress), name); } else if (commandLine.hasOption("l")) { String contractAddress = commandLine.getOptionValue("l"); if (contractAddress == null) { System.out.println("Error. Need 1 parameters: contract address"); System.out.println(""); printHelp(options); return; } manager.setManager(EthAddress.of(contractAddress)); manager.listContractData(EthAddress.of(contractAddress)); } else if (commandLine.hasOption("cic")) { String[] values = commandLine.getOptionValues("cic"); if (values == null || values.length != 6) { System.out.println("Error. Need 6 itemName, textHash, url, lifeTime, price"); System.out.println(""); printHelp(options); return; } String contractAddress = values[0]; String itemName = values[1]; String textHash = values[2]; String url = values[3]; String lifeTime = values[4]; String price = values[5]; manager.setManager(EthAddress.of(contractAddress)); manager.createIssuerContract(itemName, textHash, url, Integer.parseInt(lifeTime), Integer.parseInt(price)); } else if (commandLine.hasOption("bli")) { String[] values = commandLine.getOptionValues("bli"); if (values == null || values.length < 2 || values.length > 3) { System.out.println( "Error. Need 2-3 issuerAddress, name, optional an address when not use the sender."); System.out.println(""); printHelp(options); return; } String issuerAddress = values[0]; String name = values[1]; String address = values.length > 2 ? values[2] : null; manager.buyLicense(issuerAddress, name, address); } else if (commandLine.hasOption("v")) { String[] values = commandLine.getOptionValues("v"); String issuerAddress = values[0]; String message = values[1]; String signature = values[2]; String publicKey = values[3]; manager.verifyLicense(issuerAddress, message, signature, publicKey); } else if (commandLine.hasOption("cs")) { String message = commandLine.getOptionValue("cs"); if (message == null) { System.out.println("Error. Need 1 parameter: message"); System.out.println(""); printHelp(options); return; } String signature = createSignature(manager.sender, message); String publicKeyString = toPublicKeyString(manager.sender); System.out.println("The signature for the message is:"); System.out.println(signature); System.out.println("The public key is:"); System.out.println(publicKeyString); } else if (commandLine.hasOption("co")) { String[] values = commandLine.getOptionValues("co"); if (values == null || values.length != 2) { System.out.println("Error. Need 2 parameters: contractAddress, newOwnerAddress"); System.out.println(""); printHelp(options); return; } String contractAddress = values[0]; String newOwner = values[1]; manager.changeOwner(EthAddress.of(contractAddress), EthAddress.of(newOwner)); } else if (commandLine.hasOption("si")) { String contractAddress = commandLine.getOptionValue("si"); if (contractAddress == null) { System.out.println("Error. Need 1 parameters: contract address"); System.out.println(""); printHelp(options); return; } manager.setManager(EthAddress.of(contractAddress)); manager.stopIssue(contractAddress); } else if (commandLine.hasOption("ppuk")) { System.out.println("Public key: " + toPublicKeyString(manager.sender)); } if (manager.licenseManager != null && commandLine.hasOption("wca")) { String[] values = commandLine.getOptionValues("wca"); String filename = values[0]; File file = new File(filename); IOUtils.write( !commandLine.hasOption("cic") ? manager.licenseManager.contractAddress.withLeading0x() : manager.licenseManager.contractInstance .contracts(manager.licenseManager.contractInstance.contractCount() - 1) .withLeading0x(), new FileOutputStream(file), "UTF-8"); } if (commandLine.hasOption("calcDeploymendCost")) { balance = balance.minus(manager.ethereum.getBalance(manager.sender)); BigDecimal divide = new BigDecimal(balance.inWei()) .divide(BigDecimal.valueOf(1_000_000_000_000_000_000L)); System.out.println("Deployment cost: " + (divide) + " in wei:" + balance.inWei() + " time need: " + (System.currentTimeMillis() - currentMili)); } } catch (Exception e) { System.out.println(e.getMessage()); printHelp(options); returnValue = 10; } } catch (ParseException e1) { System.out.println(e1.getMessage()); printHelp(options); returnValue = 10; } if (!dontExit) System.exit(returnValue); }
From source file:ch.cyclops.gatekeeper.Main.java
public static void main(String[] args) throws Exception { CompositeConfiguration config = new CompositeConfiguration(); config.addConfiguration(new SystemConfiguration()); if (args.length > 0) config.addConfiguration(new PropertiesConfiguration(args[args.length - 1])); //setting up the logging framework now Logger.getRootLogger().getLoggerRepository().resetConfiguration(); ConsoleAppender console = new ConsoleAppender(); //create appender //configure the appender String PATTERN = "%d [%p|%C{1}|%M|%L] %m%n"; console.setLayout(new PatternLayout(PATTERN)); String logConsoleLevel = config.getProperty("log.level.console").toString(); switch (logConsoleLevel) { case ("INFO"): console.setThreshold(Level.INFO); break;/*from ww w .ja va 2 s. c om*/ case ("DEBUG"): console.setThreshold(Level.DEBUG); break; case ("WARN"): console.setThreshold(Level.WARN); break; case ("ERROR"): console.setThreshold(Level.ERROR); break; case ("FATAL"): console.setThreshold(Level.FATAL); break; case ("OFF"): console.setThreshold(Level.OFF); break; default: console.setThreshold(Level.ALL); } console.activateOptions(); //add appender to any Logger (here is root) Logger.getRootLogger().addAppender(console); String logFileLevel = config.getProperty("log.level.file").toString(); String logFile = config.getProperty("log.file").toString(); if (logFile != null && logFile.length() > 0) { FileAppender fa = new FileAppender(); fa.setName("FileLogger"); fa.setFile(logFile); fa.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n")); switch (logFileLevel) { case ("INFO"): fa.setThreshold(Level.INFO); break; case ("DEBUG"): fa.setThreshold(Level.DEBUG); break; case ("WARN"): fa.setThreshold(Level.WARN); break; case ("ERROR"): fa.setThreshold(Level.ERROR); break; case ("FATAL"): fa.setThreshold(Level.FATAL); break; case ("OFF"): fa.setThreshold(Level.OFF); break; default: fa.setThreshold(Level.ALL); } fa.setAppend(true); fa.activateOptions(); //add appender to any Logger (here is root) Logger.getRootLogger().addAppender(fa); } //now logger configuration is done, we can start using it. Logger mainLogger = Logger.getLogger("gatekeeper-driver.Main"); mainLogger.debug("Driver loaded properly"); if (args.length > 0) { GKDriver gkDriver = new GKDriver(args[args.length - 1], 1, "Eq7K8h9gpg"); System.out.println("testing if admin: " + gkDriver.isAdmin(1, 0)); ArrayList<String> uList = gkDriver.getUserList(0); //the argument is the starting count of number of allowed //internal attempts. if (uList != null) { mainLogger.info("Received user list from Gatekeeper! Count: " + uList.size()); for (int i = 0; i < uList.size(); i++) mainLogger.info(uList.get(i)); } boolean authResponse = gkDriver.simpleAuthentication(1, "Eq7K8h9gpg"); if (authResponse) mainLogger.info("Authentication attempt was successful."); else mainLogger.warn("Authentication attempt failed!"); String sName = "myservice-" + System.currentTimeMillis(); HashMap<String, String> newService = gkDriver.registerService(sName, "this is my new cool service", 0); String sKey = ""; if (newService != null) { mainLogger.info("Service registration was successful! Got:" + newService.get("uri") + ", Key=" + newService.get("key")); sKey = newService.get("key"); } else { mainLogger.warn("Service registration failed!"); } int newUserId = gkDriver.registerUser("user-" + System.currentTimeMillis(), "pass1234", false, sName, 0); if (newUserId != -1) mainLogger.info("User registration was successful. Received new id: " + newUserId); else mainLogger.warn("User registration failed!"); String token = gkDriver.generateToken(newUserId, "pass1234"); boolean isValidToken = gkDriver.validateToken(token, newUserId); if (isValidToken) mainLogger.info("The token: " + token + " is successfully validated for user-id: " + newUserId); else mainLogger.warn("Token validation was unsuccessful! Token: " + token + ", user-id: " + newUserId); ArrayList<String> sList = gkDriver.getServiceList(0); //the argument is the starting count of number of allowed //internal attempts. if (sList != null) { mainLogger.info("Received service list from Gatekeeper! Count: " + sList.size()); for (int i = 0; i < sList.size(); i++) mainLogger.info(sList.get(i)); } isValidToken = gkDriver.validateToken(token, sKey); if (isValidToken) mainLogger.info("The token: " + token + " is successfully validated for user-id: " + newUserId + " against s-key:" + sKey); else mainLogger.warn("Token validation was unsuccessful! Token: " + token + ", user-id: " + newUserId + ", s-key: " + sKey); boolean deleteResult = gkDriver.deleteUser(newUserId, 0); if (deleteResult) mainLogger.info("User with id: " + newUserId + " was deleted successfully."); else mainLogger.warn("User with id: " + newUserId + " could not be deleted successfully!"); } }
From source file:de.hpi.fgis.hdrs.tools.Loader.java
public static void main(String[] args) throws IOException { if (2 > args.length) { System.out.println(usage); System.out.println(options); System.exit(1);//from w w w .j a v a 2s . c om } if (0 > args[0].indexOf(':')) { args[0] += ":" + Configuration.DEFAULT_RPC_PORT; } Configuration conf = Configuration.create(); Client client = new Client(conf, args[0]); File[] files; String options = ""; if (args[1].startsWith("-")) { options = args[1]; if (3 > args.length) { System.out.println(usage); System.exit(1); } if (0 < options.indexOf('d')) { File dir = new File(args[2]); if (!dir.isDirectory()) { throw new IOException("Directory does not exist."); } files = dir.listFiles(); } else { files = new File[] { new File(args[2]) }; } } else { files = new File[] { new File(args[1]) }; } boolean quiet = 0 < options.indexOf('q'); boolean context = 0 < options.indexOf('c'); boolean bench = 0 < options.indexOf('b'); List<BenchSample> benchSamples = null; if (bench) { benchSamples = new ArrayList<BenchSample>(); } long timeStalled = 0; long timeRouterUpdate = 0; long abortedTransactions = 0; long nBytesTotal = 0; long nTriplesTotal = 0; long timeTotal = 0; for (int i = 0; i < files.length; ++i) { Closeable source = null; TripleScanner scanner = null; try { if (0 < options.indexOf('t')) { TripleFileReader reader = new TripleFileReader(files[i]); reader.open(); scanner = reader.getScanner(); source = reader; } else if (0 < options.indexOf('z')) { GZIPInputStream stream = new GZIPInputStream(new FileInputStream(files[i])); BTCParser parser = new BTCParser(); parser.setSkipContext(!context); scanner = new StreamScanner(stream, parser); source = stream; } else { BTCParser parser = new BTCParser(); parser.setSkipContext(!context); FileSource file = new FileSource(files[i], parser); scanner = file.getScanner(); source = file; } } catch (IOException ioe) { System.out.println("Error: Couldn't open " + files[i] + ". See log for details."); LOG.error("Error: Couldn't open " + files[i] + ":", ioe); continue; } long nBytes = 0; long nTriples = 0; long time = System.currentTimeMillis(); TripleOutputStream out = client.getOutputStream(); while (scanner.next()) { Triple t = scanner.pop(); out.add(t); nBytes += t.serializedSize(); nTriples++; if (!quiet && 0 == (nTriples % (16 * 1024))) { System.out.print(String.format("\rloading... %d triples (%.2f MB, %.2f MB/s)", nTriples, LogFormatUtil.MB(nBytes), LogFormatUtil.MBperSec(nBytes, System.currentTimeMillis() - time))); } } out.close(); time = System.currentTimeMillis() - time; scanner.close(); source.close(); if (!quiet) { System.out.print("\r"); } System.out.println(String.format("%s: %d triples (%.2f MB) loaded " + "in %.2f seconds (%.2f MB/s)", files[i], nTriples, LogFormatUtil.MB(nBytes), time / 1000.0, LogFormatUtil.MBperSec(nBytes, time))); nBytesTotal += nBytes; nTriplesTotal += nTriples; timeTotal += time; timeStalled += out.getTimeStalled(); timeRouterUpdate += out.getTimeRouterUpdate(); abortedTransactions += out.getAbortedTransactions(); if (bench) { benchSamples.add(new BenchSample(time, nTriples, nBytes)); } } client.close(); if (0 == nTriplesTotal) { System.out.println("No triples loaded."); return; } System.out.println( String.format("Done loading. Totals: %d triples (%.2f MB) loaded " + "in %.2f seconds (%.2f MB/s)", nTriplesTotal, LogFormatUtil.MB(nBytesTotal), timeTotal / 1000.0, LogFormatUtil.MBperSec(nBytesTotal, timeTotal))); System.out.println(String.format( " Client stats. Stalled: %.2f s RouterUpdate: %.2f s" + " AbortedTransactions: %d", timeStalled / 1000.0, timeRouterUpdate / 1000.0, abortedTransactions)); if (bench) { System.out.println(); System.out.println("Benchmark Samples:"); System.out.println("time\tsum T\tsum MB\tMB/s"); System.out.println(String.format("%.2f\t%d\t%.2f\t%.2f", 0f, 0, 0f, 0f)); long time = 0, nTriples = 0, nBytes = 0; for (BenchSample sample : benchSamples) { time += sample.time; nTriples += sample.nTriples; nBytes += sample.nBytes; System.out.println(String.format("%.2f\t%d\t%.2f\t%.2f", time / 1000.0, nTriples, LogFormatUtil.MB(nBytes), LogFormatUtil.MBperSec(sample.nBytes, sample.time))); } } }
From source file:com.pivotal.gfxd.demo.loader.LoadRunner.java
public static void main(String[] args) { final String CSV_FILE = args[0]; long startTime = System.currentTimeMillis(); try (ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:context.xml")) { LoadRunner runner = (LoadRunner) context.getBean("loadRunner"); runner.run(CSV_FILE);/* ww w. j a v a2 s . co m*/ } long endTime = System.currentTimeMillis(); logger.info("Total execution time: " + (endTime - startTime) + "ms"); }
From source file:edu.berkeley.sparrow.examples.ProtoFrontendAsync.java
public static void main(String[] args) { try {//from w w w . ja v a 2 s .c om OptionParser parser = new OptionParser(); parser.accepts("c", "configuration file").withRequiredArg().ofType(String.class); parser.accepts("help", "print help statement"); OptionSet options = parser.parse(args); if (options.has("help")) { parser.printHelpOn(System.out); System.exit(-1); } // Logger configuration: log to the console BasicConfigurator.configure(); LOG.setLevel(Level.DEBUG); Configuration conf = new PropertiesConfiguration(); if (options.has("c")) { String configFile = (String) options.valueOf("c"); conf = new PropertiesConfiguration(configFile); } Random r = new Random(); double lambda = conf.getDouble("job_arrival_rate_s", DEFAULT_JOB_ARRIVAL_RATE_S); int tasksPerJob = conf.getInt("tasks_per_job", DEFAULT_TASKS_PER_JOB); int benchmarkIterations = conf.getInt("benchmark.iterations", DEFAULT_BENCHMARK_ITERATIONS); int benchmarkId = conf.getInt("benchmark.id", DEFAULT_TASK_BENCHMARK); int schedulerPort = conf.getInt("scheduler_port", SchedulerThrift.DEFAULT_SCHEDULER_THRIFT_PORT); TProtocolFactory factory = new TBinaryProtocol.Factory(); TAsyncClientManager manager = new TAsyncClientManager(); long lastLaunch = System.currentTimeMillis(); // Loop and generate tasks launches while (true) { // Lambda is the arrival rate in S, so we need to multiply the result here by // 1000 to convert to ms. long delay = (long) (generateInterarrivalDelay(r, lambda) * 1000); long curLaunch = lastLaunch + delay; long toWait = Math.max(0, curLaunch - System.currentTimeMillis()); lastLaunch = curLaunch; if (toWait == 0) { LOG.warn("Generated workload not keeping up with real time."); } List<TTaskSpec> tasks = generateJob(tasksPerJob, benchmarkId, benchmarkIterations); TUserGroupInfo user = new TUserGroupInfo(); user.setUser("*"); user.setGroup("*"); TSchedulingRequest req = new TSchedulingRequest(); req.setApp("testApp"); req.setTasks(tasks); req.setUser(user); TNonblockingTransport tr = new TNonblockingSocket("localhost", schedulerPort); SchedulerService.AsyncClient client = new SchedulerService.AsyncClient(factory, manager, tr); //client.registerFrontend("testApp", new RegisterCallback()); client.submitJob(req, new SubmitCallback(req, tr)); } } catch (Exception e) { LOG.error("Fatal exception", e); } }
From source file:hyperloglog.tools.HyperLogLogCLI.java
public static void main(String[] args) { Options options = new Options(); addOptions(options);/*from ww w .j a v a2 s. c o m*/ CommandLineParser parser = new BasicParser(); CommandLine cli = null; long n = 0; long seed = 123; EncodingType enc = EncodingType.SPARSE; int p = 14; int hb = 64; boolean bitPack = true; boolean noBias = true; int unique = -1; String filePath = null; BufferedReader br = null; String outFile = null; String inFile = null; FileOutputStream fos = null; DataOutputStream out = null; FileInputStream fis = null; DataInputStream in = null; try { cli = parser.parse(options, args); if (!(cli.hasOption('n') || cli.hasOption('f') || cli.hasOption('d'))) { System.out.println("Example usage: hll -n 1000 " + "<OR> hll -f /tmp/input.txt " + "<OR> hll -d -i /tmp/out.hll"); usage(options); return; } if (cli.hasOption('n')) { n = Long.parseLong(cli.getOptionValue('n')); } if (cli.hasOption('e')) { String value = cli.getOptionValue('e'); if (value.equals(EncodingType.DENSE.name())) { enc = EncodingType.DENSE; } } if (cli.hasOption('p')) { p = Integer.parseInt(cli.getOptionValue('p')); if (p < 4 && p > 16) { System.out.println("Warning! Out-of-range value specified for p. Using to p=14."); p = 14; } } if (cli.hasOption('h')) { hb = Integer.parseInt(cli.getOptionValue('h')); } if (cli.hasOption('c')) { noBias = Boolean.parseBoolean(cli.getOptionValue('c')); } if (cli.hasOption('b')) { bitPack = Boolean.parseBoolean(cli.getOptionValue('b')); } if (cli.hasOption('f')) { filePath = cli.getOptionValue('f'); br = new BufferedReader(new FileReader(new File(filePath))); } if (filePath != null && cli.hasOption('n')) { System.out.println("'-f' (input file) specified. Ignoring -n."); } if (cli.hasOption('s')) { if (cli.hasOption('o')) { outFile = cli.getOptionValue('o'); fos = new FileOutputStream(new File(outFile)); out = new DataOutputStream(fos); } else { System.err.println("Specify output file. Example usage: hll -s -o /tmp/out.hll"); usage(options); return; } } if (cli.hasOption('d')) { if (cli.hasOption('i')) { inFile = cli.getOptionValue('i'); fis = new FileInputStream(new File(inFile)); in = new DataInputStream(fis); } else { System.err.println("Specify input file. Example usage: hll -d -i /tmp/in.hll"); usage(options); return; } } // return after deserialization if (fis != null && in != null) { long start = System.currentTimeMillis(); HyperLogLog deserializedHLL = HyperLogLogUtils.deserializeHLL(in); long end = System.currentTimeMillis(); System.out.println(deserializedHLL.toString()); System.out.println("Count after deserialization: " + deserializedHLL.count()); System.out.println("Deserialization time: " + (end - start) + " ms"); return; } // construct hll and serialize it if required HyperLogLog hll = HyperLogLog.builder().enableBitPacking(bitPack).enableNoBias(noBias).setEncoding(enc) .setNumHashBits(hb).setNumRegisterIndexBits(p).build(); if (br != null) { Set<String> hashset = new HashSet<String>(); String line; while ((line = br.readLine()) != null) { hll.addString(line); hashset.add(line); } n = hashset.size(); } else { Random rand = new Random(seed); for (int i = 0; i < n; i++) { if (unique < 0) { hll.addLong(rand.nextLong()); } else { int val = rand.nextInt(unique); hll.addLong(val); } } } long estCount = hll.count(); System.out.println("Actual count: " + n); System.out.println(hll.toString()); System.out.println("Relative error: " + HyperLogLogUtils.getRelativeError(n, estCount) + "%"); if (fos != null && out != null) { long start = System.currentTimeMillis(); HyperLogLogUtils.serializeHLL(out, hll); long end = System.currentTimeMillis(); System.out.println("Serialized hyperloglog to " + outFile); System.out.println("Serialized size: " + out.size() + " bytes"); System.out.println("Serialization time: " + (end - start) + " ms"); out.close(); } } catch (ParseException e) { System.err.println("Invalid parameter."); usage(options); } catch (NumberFormatException e) { System.err.println("Invalid type for parameter."); usage(options); } catch (FileNotFoundException e) { System.err.println("Specified file not found."); usage(options); } catch (IOException e) { System.err.println("Exception occured while reading file."); usage(options); } }
From source file:avantssar.aslanpp.testing.Tester.java
public static void main(String[] args) { Debug.initLog(LogLevel.INFO);/*from w ww. j av a 2s . c o m*/ TesterCommandLineOptions options = new TesterCommandLineOptions(); try { options.getParser().parseArgument(args); options.ckeckAtEnd(); } catch (CmdLineException ex) { reportException("Inconsistent options.", ex, System.err); options.showShortHelp(System.err); return; } if (options.isShowHelp()) { options.showLongHelp(System.out); return; } ASLanPPConnectorImpl translator = new ASLanPPConnectorImpl(); if (options.isShowVersion()) { System.out.println(translator.getFullTitleLine()); return; } ISpecificationBundleProvider sbp; File realInDir; if (options.isLibrary()) { if (options.getHornClausesLevel() != HornClausesLevel.ALL) { System.out.println("When checking the internal library we output all Horn clauses."); options.setHornClausesLevel(HornClausesLevel.ALL); } if (!options.isStripOutput()) { System.out.println( "When checking the internal library, the ouput is stripped of comments and line information."); options.setStripOutput(true); } File modelsDir = new File(FilenameUtils.concat(options.getOut().getAbsolutePath(), "_models")); try { FileUtils.forceMkdir(modelsDir); } catch (IOException e1) { System.out.println("Failed to create models folder: " + e1.getMessage()); Debug.logger.error("Failed to create models folder.", e1); } realInDir = modelsDir; sbp = new LibrarySpecificationsProvider(modelsDir.getAbsolutePath()); } else { realInDir = options.getIn(); sbp = new DiskSpecificationsProvider(options.getIn().getAbsolutePath()); } System.setProperty(EntityManager.ASLAN_ENVVAR, sbp.getASLanPath()); // try { // EntityManager.loadASLanPath(); // } // catch (IOException e) { // System.out.println("Exception while reloading ASLANPATH: " + // e.getMessage()); // Debug.logger.error("Exception while loading ASLANPATH.", e); // } try { bm = BackendsManager.instance(); if (bm != null) { for (IBackendRunner br : bm.getBackendRunners()) { System.out.println(br.getFullDescription()); if (br.getTimeout() > finalTimeout) { finalTimeout = br.getTimeout(); } } } } catch (IOException e) { System.out.println("Failed to load backends: " + e); } int threadsCount = 50; if (options.getThreads() > 0) { threadsCount = options.getThreads(); } System.out.println("Will launch " + threadsCount + " threads in parallel (+ will show that a thread starts, - that a thread ends)."); TranslationReport rep = new TranslationReport( bm != null ? bm.getBackendRunners() : new ArrayList<IBackendRunner>(), options.getOut()); long startTime = System.currentTimeMillis(); int specsCount = 0; pool = Executors.newFixedThreadPool(threadsCount); for (ITestTask task : sbp) { doTest(rep, task, realInDir, options.getOut(), translator, options, System.err); specsCount++; } pool.shutdown(); String reportFile = FilenameUtils.concat(options.getOut().getAbsolutePath(), "index.html"); try { while (!pool.awaitTermination(finalTimeout, TimeUnit.SECONDS)) { } } catch (InterruptedException e) { Debug.logger.error("Interrupted while waiting for pool termination.", e); System.out.println("Interrupted while waiting for pool termination: " + e.getMessage()); System.out.println("The report may be incomplete."); } long endTime = System.currentTimeMillis(); long duration = (endTime - startTime) / 1000; System.out.println(); System.out.println(specsCount + " specifications checked in " + duration + " seconds."); rep.report(reportFile); System.out.println("You can find an overview report at '" + reportFile + "'."); }