List of usage examples for java.lang System currentTimeMillis
@HotSpotIntrinsicCandidate public static native long currentTimeMillis();
From source file:com.xoom.rabbit.test.Main.java
public static void main(String[] args) throws InterruptedException { if (args.length != 9) { System.out.println(/* w ww. j a v a 2 s.c om*/ "usage: java -jar target/rabbit-tester-0.1-SNAPSHOT-standalone.jar [consumer_threads] [number_of_messages] [amqp_host] [amqp_port] [produce] [consume] [message size in bytes] [username] [password]"); return; } final long startTime = System.currentTimeMillis(); int consumerThreads = Integer.parseInt(args[0]); final int messages = Integer.parseInt(args[1]); String host = args[2]; int port = Integer.parseInt(args[3]); boolean produce = Boolean.parseBoolean(args[4]); boolean consume = Boolean.parseBoolean(args[5]); final int messageSize = Integer.parseInt(args[6]); String username = args[7]; String password = args[8]; if (produce) { System.out.println("Sending " + messages + " messages to " + host + ":" + port); } if (consume) { System.out.println("Consuming " + messages + " messages from " + host + ":" + port); } if (!produce && !consume) { System.out.println("Not producing or consuming any messages."); } CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host, port); connectionFactory.setUsername(username); connectionFactory.setPassword(password); connectionFactory.setChannelCacheSize(consumerThreads + 1); RabbitAdmin amqpAdmin = new RabbitAdmin(connectionFactory); DirectExchange exchange = new DirectExchange(EXCHANGE_NAME, true, false); Queue queue = new Queue(QUEUE_NAME); amqpAdmin.declareExchange(exchange); amqpAdmin.declareQueue(queue); amqpAdmin.declareBinding(BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY)); final AmqpTemplate amqpTemplate = new RabbitTemplate(connectionFactory); final CountDownLatch producerLatch = new CountDownLatch(messages); final CountDownLatch consumerLatch = new CountDownLatch(messages); SimpleMessageListenerContainer listenerContainer = null; if (consume) { listenerContainer = new SimpleMessageListenerContainer(); listenerContainer.setConnectionFactory(connectionFactory); listenerContainer.setQueueNames(QUEUE_NAME); listenerContainer.setConcurrentConsumers(consumerThreads); listenerContainer.setMessageListener(new MessageListener() { @Override public void onMessage(Message message) { if (consumerLatch.getCount() == 1) { System.out.println("Finished consuming " + messages + " messages in " + (System.currentTimeMillis() - startTime) + "ms"); } consumerLatch.countDown(); } }); listenerContainer.start(); } if (produce) { while (producerLatch.getCount() > 0) { try { byte[] message = new byte[messageSize]; RND.nextBytes(message); amqpTemplate.send(EXCHANGE_NAME, ROUTING_KEY, new Message(message, new MessageProperties())); producerLatch.countDown(); } catch (Exception e) { System.out.println("Failed to send message " + (messages - producerLatch.getCount()) + " will retry forever."); } } } if (consume) { consumerLatch.await(); listenerContainer.shutdown(); } connectionFactory.destroy(); }
From source file:eu.scape_project.arc2warc.Arc2WarcMigration.java
/** * Main entry point./* w w w .j a va 2 s . c o m*/ * * @param args * @throws java.io.IOException * @throws org.apache.commons.cli.ParseException */ public static void main(String[] args) throws IOException, ParseException { Configuration conf = new Configuration(); // Command line interface config = new Arc2WarcMigrationConfig(); CommandLineParser cmdParser = new PosixParser(); GenericOptionsParser gop = new GenericOptionsParser(conf, args); Arc2WarcMigrationOptions a2wopt = new Arc2WarcMigrationOptions(); CommandLine cmd = cmdParser.parse(a2wopt.options, gop.getRemainingArgs()); if ((args.length == 0) || (cmd.hasOption(a2wopt.HELP_OPT))) { a2wopt.exit("Help", 0); } else { a2wopt.initOptions(cmd, config); } Arc2WarcMigration a2wm = new Arc2WarcMigration(); long startMillis = System.currentTimeMillis(); File input = new File(config.getInputStr()); if (input.isDirectory()) { config.setDirectoryInput(true); a2wm.traverseDir(input); } else { migrate(input); } long elapsedTimeMillis = System.currentTimeMillis() - startMillis; LOG.info("Processing time (sec): " + elapsedTimeMillis / 1000F); System.exit(0); }
From source file:ch.rasc.wampspring.demo.client.Publisher.java
public static void main(String[] args) throws InterruptedException { WebSocketClient webSocketClient = new StandardWebSocketClient(); final JsonFactory jsonFactory = new MappingJsonFactory(new ObjectMapper()); final CountDownLatch welcomeLatch = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(1_000_000); TextWebSocketHandler handler = new TextWebSocketHandler() { @Override//from w w w.j a v a 2 s. co m protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { WampMessage wampMessage = WampMessage.fromJson(jsonFactory, message.getPayload()); if (wampMessage instanceof WelcomeMessage) { latch.countDown(); } } }; Long[] start = new Long[1]; ListenableFuture<WebSocketSession> future = webSocketClient.doHandshake(handler, "ws://localhost:8080/wamp"); future.addCallback(wss -> { // Waiting for WELCOME message try { welcomeLatch.await(5, TimeUnit.SECONDS); start[0] = System.currentTimeMillis(); for (int i = 0; i < 1_000_000; i++) { PublishMessage publishMessage = new PublishMessage("/test/myqueue", i); try { wss.sendMessage(new TextMessage(publishMessage.toJson(jsonFactory))); } catch (Exception e) { System.out.println("ERROR SENDING PUBLISH_MESSAGE" + e); } latch.countDown(); } } catch (Exception e1) { System.out.println("SENDING PUBLISH MESSAGES: " + e1); } }, t -> { System.out.println("DO HANDSHAKE ERROR: " + t); System.exit(1); }); if (!latch.await(3, TimeUnit.MINUTES)) { System.out.println("SOMETHING WENT WRONG"); } System.out.println((System.currentTimeMillis() - start[0]) / 1000 + " seconds"); }
From source file:com.cloudhopper.sxmp.SubmitMain.java
static public void main(String[] args) throws Exception { String url = "http://localhost:9080/api/sxmp/1.0"; // create a submit request SubmitRequest submit = new SubmitRequest(); submit.setAccount(new Account("customer1", "password1")); submit.setDeliveryReport(Boolean.TRUE); MobileAddress sourceAddr = new MobileAddress(); sourceAddr.setAddress(MobileAddress.Type.NETWORK, "40404"); submit.setSourceAddress(sourceAddr); submit.setOperatorId(24);/*w w w.jav a2 s. c om*/ MobileAddress destAddr = new MobileAddress(); destAddr.setAddress(MobileAddress.Type.INTERNATIONAL, "+14155551212"); submit.setDestinationAddress(destAddr); submit.setText( "Test abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijjabcdefghijjabcdefghijjabcdefghijjabcdefghijjabcdefghijjabcdefghijjabcdefghijbcdefghij", TextEncoding.UTF_8); //submit.setText("Hello World"); // Get file to be posted HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); client.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); long totalStart = System.currentTimeMillis(); int count = 1; for (int i = 0; i < count; i++) { long start = System.currentTimeMillis(); // execute request try { HttpPost post = new HttpPost(url); //ByteArrayEntity entity = new ByteArrayEntity(data); StringEntity entity = new StringEntity(SxmpWriter.createString(submit)); entity.setContentType("text/xml; charset=\"iso-8859-1\""); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = client.execute(post, responseHandler); long stop = System.currentTimeMillis(); logger.debug("----------------------------------------"); logger.debug("Response took " + (stop - start) + " ms"); logger.debug(responseBody); logger.debug("----------------------------------------"); } finally { // do nothing } } long totalEnd = System.currentTimeMillis(); logger.debug("Response took " + (totalEnd - totalStart) + " ms for " + count + " requests"); double seconds = ((double) (totalEnd - totalStart)) / 1000; double smspersec = ((double) count) / seconds; logger.debug("SMS / Sec: " + DecimalUtil.toString(smspersec, 2)); }
From source file:org.eclipseplugins.impexeditor.http.ImpexHttpClient.java
public static void main(final String[] args) throws Exception { final ImpexHttpClient impexHttpClient = new ImpexHttpClient("http://localhost:9001/hac"); final long startTime = System.currentTimeMillis(); final Map<String, JsonArray> allatypes = new HashMap<String, JsonArray>(); for (final JsonValue type : impexHttpClient.getAllTypes()) { allatypes.put(type.asString(),/*from ww w. ja va 2 s. c om*/ impexHttpClient.getTypeandAttribute(type.asString()).get("attributes").asArray()); } for (final String type : allatypes.keySet()) { System.out.println("type :" + type); for (final JsonValue string : allatypes.get(type)) { System.out.println("---- " + string.asString()); } } final long stopTime = System.currentTimeMillis(); final long elapsedTime = stopTime - startTime; System.out.println("Success elapsed time in seconde " + TimeUnit.MILLISECONDS.toSeconds(elapsedTime)); }
From source file:MeCabBench.java
public static void main(String[] args) { try {//ww w.j av a2s. c o m if (args.length == 0) { System.out.println("usage: java MeCabBench file [file ..]"); System.exit(2); } Tagger tagger = new Tagger(new String[] { "java", "-d", dicPath }); long processed = 0; long nbytes = 0; long nchars = 0; long start = System.currentTimeMillis(); for (int a = 0; a < args.length; a++) { String text = ""; try { RandomAccessFile raf = new RandomAccessFile(args[a], "r"); byte[] buf = new byte[(int) raf.length()]; raf.readFully(buf); raf.close(); text = new String(buf, encoding); nbytes += buf.length; nchars += text.length(); } catch (IOException ioe) { log.error(ioe); continue; } long s_start = System.currentTimeMillis(); for (int c = 0; c < repeat; c++) doWork(tagger, text); long s_end = System.currentTimeMillis(); processed += (s_end - s_start); } long end = System.currentTimeMillis(); System.out.println("number of files: " + args.length); System.out.println("number of repeat: " + repeat); System.out.println("number of bytes: " + nbytes); System.out.println("number of chars: " + nchars); System.out.println("total time elapsed: " + (end - start) + " msec."); System.out.println("analysis time: " + (processed) + " msec."); } catch (Exception e) { e.printStackTrace(System.err); System.exit(1); } }
From source file:com.taobao.tddl.common.SQLPreParserTest.java
public static void main(String[] args) throws IOException { //String fileName = "D:/12_code/tddl/trunk/tddl/tddl-parser/sqlsummary-icsg-db0-db15-group-20100901100337-export.xlsx"; //String fileName = "D:/12_code/tddl/trunk/tddl/tddl-parser/sqlsummary-tcsg-instance-group-20100901100641-export.xlsx"; int count = 0; long time = 0; File home = new File(System.getProperty("user.dir") + "/appsqls"); for (File f : home.listFiles()) { if (f.isDirectory() || !f.getName().endsWith(".xlsx")) { continue; }/* ww w . jav a2 s. com*/ log.info("---------------------- " + f.getAbsolutePath()); faillog.info("---------------------- " + f.getAbsolutePath()); Workbook wb = new XSSFWorkbook(new FileInputStream(f)); Sheet sheet = wb.getSheetAt(0); for (Row row : sheet) { Cell cell = row.getCell(2); if (cell != null && cell.getCellType() == Cell.CELL_TYPE_STRING) { String sql = cell.getStringCellValue(); long t0 = System.currentTimeMillis(); String tableName = SQLPreParser.findTableName(sql); time += System.currentTimeMillis() - t0; count++; log.info(tableName + " <-- " + sql); if (tableName == null) { sql = sql.trim().toLowerCase(); if (isCRUD(sql)) { System.out.println("failed:" + sql); faillog.error("failed:" + sql); } } } } wb = null; } faillog.fatal("------------------------------- finished --------------------------"); faillog.fatal(count + " sql parsed, total time:" + time + ". average time use per sql:" + (double) time / count + "ms/sql"); }
From source file:com.alibaba.rocketmq.example.benchmark.Consumer.java
public static void main(String[] args) throws MQClientException { Options options = ServerUtil.buildCommandlineOptions(new Options()); CommandLine commandLine = ServerUtil.parseCmdLine("benchmarkConsumer", args, buildCommandlineOptions(options), new PosixParser()); if (null == commandLine) { System.exit(-1);//from ww w .j ava 2 s . co m } final String topic = commandLine.hasOption('t') ? commandLine.getOptionValue('t').trim() : "BenchmarkTest"; final String groupPrefix = commandLine.hasOption('g') ? commandLine.getOptionValue('g').trim() : "benchmark_consumer"; final String isPrefixEnable = commandLine.hasOption('p') ? commandLine.getOptionValue('p').trim() : "true"; String group = groupPrefix; if (Boolean.parseBoolean(isPrefixEnable)) { group = groupPrefix + "_" + Long.toString(System.currentTimeMillis() % 100); } System.out.printf("topic %s group %s prefix %s%n", topic, group, isPrefixEnable); final StatsBenchmarkConsumer statsBenchmarkConsumer = new StatsBenchmarkConsumer(); final Timer timer = new Timer("BenchmarkTimerThread", true); final LinkedList<Long[]> snapshotList = new LinkedList<Long[]>(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { snapshotList.addLast(statsBenchmarkConsumer.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 consumeTps = (long) (((end[1] - begin[1]) / (double) (end[0] - begin[0])) * 1000L); final double averageB2CRT = (end[2] - begin[2]) / (double) (end[1] - begin[1]); final double averageS2CRT = (end[3] - begin[3]) / (double) (end[1] - begin[1]); System.out.printf( "Consume TPS: %d Average(B2C) RT: %7.3f Average(S2C) RT: %7.3f MAX(B2C) RT: %d MAX(S2C) RT: %d%n", consumeTps, averageB2CRT, averageS2CRT, end[4], end[5]); } } @Override public void run() { try { this.printStats(); } catch (Exception e) { e.printStackTrace(); } } }, 10000, 10000); DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(group); consumer.setInstanceName(Long.toString(System.currentTimeMillis())); consumer.subscribe(topic, "*"); consumer.registerMessageListener(new MessageListenerConcurrently() { @Override public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) { MessageExt msg = msgs.get(0); long now = System.currentTimeMillis(); statsBenchmarkConsumer.getReceiveMessageTotalCount().incrementAndGet(); long born2ConsumerRT = now - msg.getBornTimestamp(); statsBenchmarkConsumer.getBorn2ConsumerTotalRT().addAndGet(born2ConsumerRT); long store2ConsumerRT = now - msg.getStoreTimestamp(); statsBenchmarkConsumer.getStore2ConsumerTotalRT().addAndGet(store2ConsumerRT); compareAndSetMax(statsBenchmarkConsumer.getBorn2ConsumerMaxRT(), born2ConsumerRT); compareAndSetMax(statsBenchmarkConsumer.getStore2ConsumerMaxRT(), store2ConsumerRT); return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } }); consumer.start(); System.out.printf("Consumer Started.%n"); }
From source file:com.tc.simple.apn.quicktests.Test.java
/** * @param args/*from www . j a v a 2s .c o m*/ */ public static void main(String[] args) { SSLSocket socket = null; try { String host = "gateway.sandbox.push.apple.com"; int port = 2195; String token = "de7f197546e41a76684f8e2d89f397ed165298d7772f4bd9b0f39c674b185b0f"; System.out.println(token.toCharArray().length); //String token = "8cebc7c08f79fa62f0994eb4298387ff930857ff8d14a50de431559cf476b223"; KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(Test.class.getResourceAsStream("egram-dev-apn.p12"), "xxxxxxxxx".toCharArray()); KeyManagerFactory keyMgrFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyMgrFactory.init(keyStore, "xxxxxxxxx".toCharArray()); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyMgrFactory.getKeyManagers(), null, null); SSLSocketFactory socketFactory = sslContext.getSocketFactory(); socket = (SSLSocket) socketFactory.createSocket(host, port); String[] cipherSuites = socket.getSupportedCipherSuites(); socket.setEnabledCipherSuites(cipherSuites); socket.startHandshake(); char[] t = token.toCharArray(); byte[] b = Hex.decodeHex(t); OutputStream outputstream = socket.getOutputStream(); String payload = "{\"aps\":{\"alert\":\"yabadabadooo\"}}"; int expiry = (int) ((System.currentTimeMillis() / 1000L) + 7200); ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bout); //command dos.writeByte(1); //id dos.writeInt(900); //expiry dos.writeInt(expiry); //token length. dos.writeShort(b.length); //token dos.write(b); //payload length dos.writeShort(payload.length()); //payload. dos.write(payload.getBytes()); byte[] byteMe = bout.toByteArray(); socket.getOutputStream().write(byteMe); socket.setSoTimeout(900); InputStream in = socket.getInputStream(); System.out.println(APNErrors.getError(in.read())); in.close(); outputstream.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
From source file:com.weibo.motan.demo.client.DemoRpcClient.java
public static void main(String[] args) throws Exception { final DescriptiveStatistics stats = new SynchronizedDescriptiveStatistics(); int threads = Integer.parseInt(args[0]); DubboBenchmark.BenchmarkMessage msg = prepareArgs(); final byte[] msgBytes = msg.toByteArray(); int n = 1000000; final CountDownLatch latch = new CountDownLatch(n); ExecutorService es = Executors.newFixedThreadPool(threads); final AtomicInteger trans = new AtomicInteger(0); final AtomicInteger transOK = new AtomicInteger(0); ApplicationContext ctx = new ClassPathXmlApplicationContext( new String[] { "classpath:motan_demo_client.xml" }); MotanDemoService service = (MotanDemoService) ctx.getBean("motanDemoReferer"); long start = System.currentTimeMillis(); for (int i = 0; i < n; i++) { es.submit(() -> {//from w w w .jav a2s. c o m try { long t = System.currentTimeMillis(); DubboBenchmark.BenchmarkMessage m = testSay(service, msgBytes); t = System.currentTimeMillis() - t; stats.addValue(t); trans.incrementAndGet(); if (m != null && m.getField1().equals("OK")) { transOK.incrementAndGet(); } } finally { latch.countDown(); } }); } latch.await(); start = System.currentTimeMillis() - start; System.out.printf("sent requests : %d\n", n); System.out.printf("received requests : %d\n", trans.get()); System.out.printf("received requests_OK : %d\n", transOK.get()); System.out.printf("throughput (TPS) : %d\n", n * 1000 / start); System.out.printf("mean: %f\n", stats.getMean()); System.out.printf("median: %f\n", stats.getPercentile(50)); System.out.printf("max: %f\n", stats.getMax()); System.out.printf("min: %f\n", stats.getMin()); System.out.printf("99P: %f\n", stats.getPercentile(90)); }