Example usage for java.lang System currentTimeMillis

List of usage examples for java.lang System currentTimeMillis

Introduction

In this page you can find the example usage for java.lang System currentTimeMillis.

Prototype

@HotSpotIntrinsicCandidate
public static native long currentTimeMillis();

Source Link

Document

Returns the current time in milliseconds.

Usage

From source file:ilarkesto.integration.ftp.FtpClient.java

public static void main(String[] args) {
    LoginData login = LoginPanel.showDialog(null, "FTP to localhost",
            new File(Sys.getUsersHomePath() + "/.ilarkesto/ftp.localhost.properties"));

    FtpClient ftp = new FtpClient("localhost", login);
    ftp.connect();/*from w w w .  j a va 2s. c o m*/
    String dirname = "test_" + System.currentTimeMillis();
    ftp.createDir(dirname);
    ftp.deleteDir(dirname);
    ftp.close();
}

From source file:com.linkedin.pinotdruidbenchmark.DruidThroughput.java

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    if (args.length != 3 && args.length != 4) {
        System.err.println(//from www . ja v  a2s .c  o  m
                "3 or 4 arguments required: QUERY_DIR, RESOURCE_URL, NUM_CLIENTS, TEST_TIME (seconds).");
        return;
    }

    File queryDir = new File(args[0]);
    String resourceUrl = args[1];
    final int numClients = Integer.parseInt(args[2]);
    final long endTime;
    if (args.length == 3) {
        endTime = Long.MAX_VALUE;
    } else {
        endTime = System.currentTimeMillis() + Integer.parseInt(args[3]) * MILLIS_PER_SECOND;
    }

    File[] queryFiles = queryDir.listFiles();
    assert queryFiles != null;
    Arrays.sort(queryFiles);

    final int numQueries = queryFiles.length;
    final HttpPost[] httpPosts = new HttpPost[numQueries];
    for (int i = 0; i < numQueries; i++) {
        HttpPost httpPost = new HttpPost(resourceUrl);
        httpPost.addHeader("content-type", "application/json");
        StringBuilder stringBuilder = new StringBuilder();
        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(queryFiles[i]))) {
            int length;
            while ((length = bufferedReader.read(CHAR_BUFFER)) > 0) {
                stringBuilder.append(new String(CHAR_BUFFER, 0, length));
            }
        }
        String query = stringBuilder.toString();
        httpPost.setEntity(new StringEntity(query));
        httpPosts[i] = httpPost;
    }

    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(numClients);

    for (int i = 0; i < numClients; i++) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                    while (System.currentTimeMillis() < endTime) {
                        long startTime = System.currentTimeMillis();
                        CloseableHttpResponse httpResponse = httpClient
                                .execute(httpPosts[RANDOM.nextInt(numQueries)]);
                        httpResponse.close();
                        long responseTime = System.currentTimeMillis() - startTime;
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(responseTime);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    executorService.shutdown();

    long startTime = System.currentTimeMillis();
    while (System.currentTimeMillis() < endTime) {
        Thread.sleep(REPORT_INTERVAL_MILLIS);
        double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND;
        int count = counter.get();
        double avgResponseTime = ((double) totalResponseTime.get()) / count;
        System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: "
                + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms");
    }
}

From source file:org.owasp.benchmark.tools.BenchmarkCrawler.java

public static void main(String[] args) throws Exception {

    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(getSSLFactory()).build();

    long start = System.currentTimeMillis();

    InputStream http = BenchmarkCrawler.class.getClassLoader()
            .getResourceAsStream("benchmark-crawler-http.xml");

    List<HttpPost> posts = parseHttpFile(httpclient, http);
    for (HttpPost post : posts) {
        try {//from   w w  w.  ja  v a2s .c o m
            sendPost(httpclient, post);
        } catch (Exception e) {
            System.err.println("\n  FAILED: " + e.getMessage());
            e.printStackTrace();
        }
    }

    long stop = System.currentTimeMillis();
    double seconds = (stop - start) / 1000;
    System.out.println("\n\nElapsed time " + seconds + " seconds");

}

From source file:ca.gnewton.lusql.core.LuSqlMain.java

/**
 * Describe <code>main</code> method here.
 *
 * @param args a <code>String</code> value
 *///  www .j av a2 s . c o m
public static final void main(final String[] args) {
    checkForSpecialArguments(args);

    long t0 = System.currentTimeMillis();
    LuSql lusql = new LuSql();
    lusql.setFieldMap(fieldMap);
    boolean optionsFlag;
    try {
        RunState state = handleOptions(lusql, args);
        switch (state) {
        case Done:
            break;
        case Work:
            // Txt file describing how index was made//
            initInfoFile(lusql);
            Util.setOut(infoOut);

            lusql.init();
            if (LuSql.isVerbose())
                printOptions(lusql);
            lusql.run();
            if (LuSql.isVerbose())
                log.info("Elapsed time: " + (System.currentTimeMillis() - t0) / 1000 + " seconds\n");
            if (infoOut != null)
                infoOut.close();
            break;
        case ExplainPlugin:
            explainPlugin();
            break;

        case ShowOptions:
        default:
            usage();
            break;
        }
    } catch (Throwable pe) {
        if (!silent) {
            pe.printStackTrace();
            usage();
        }
        System.exit(42);
    }
}

From source file:com.threeglav.sh.bauk.main.StreamHorizonEngine.java

public static void main(final String[] args) throws Exception {
    printRuntimeInfo();/*  ww  w .j a  v  a 2s .  c om*/
    final long start = System.currentTimeMillis();
    LOG.info("To run in test mode set system parameter {}=true",
            BaukEngineConfigurationConstants.IDEMPOTENT_FEED_PROCESSING_PARAM_NAME);
    Runtime.getRuntime().addShutdownHook(new ShutdownHook());
    final BaukConfiguration conf = findConfiguration();
    if (conf != null) {
        ConfigurationProperties.setBaukProperties(conf.getProperties());
        final ConfigurationValidator configValidator = new ConfigurationValidator(conf);
        try {
            configValidator.validate();
        } catch (final Exception exc) {
            BaukUtil.logEngineMessageSync("Error while validating configuration: " + exc.getMessage());
            LOG.error("", exc);
            System.exit(-1);
        }
        remotingHandler = new RemotingServer();
        remotingHandler.start();
        createProcessingRoutes(conf);
        final boolean throughputTestingMode = ConfigurationProperties
                .getSystemProperty(BaukEngineConfigurationConstants.THROUGHPUT_TESTING_MODE_PARAM_NAME, false);
        if (throughputTestingMode) {
            BaukUtil.logEngineMessageSync(
                    "ENGINE IS RUNNING IN THROUGHPUT TESTING MODE! ONE INPUT FEED FILE PER THREAD WILL BE CACHED AND PROCESSED REPEATEDLY!!!");
        }
        instanceStartTime = System.currentTimeMillis();
        final boolean isMultiInstance = ConfigurationProperties.isConfiguredPartitionedMultipleInstances();
        if (isMultiInstance) {
            final int totalPartitionsCount = ConfigurationProperties.getSystemProperty(
                    BaukEngineConfigurationConstants.MULTI_INSTANCE_PARTITION_COUNT_PARAM_NAME, -1);
            final String myUniqueIdentifier = ConfigurationProperties.getBaukInstanceIdentifier();
            BaukUtil.logEngineMessageSync("Configured to run in multi-instance mode of " + totalPartitionsCount
                    + " instances in total. My unique identifier is " + myUniqueIdentifier);
        }
        BaukUtil.logEngineMessageSync("Finished initialization! Started counting uptime");
        startProcessing();
        final long total = System.currentTimeMillis() - start;
        final long totalSec = total / 1000;
        final boolean detectBaukInstances = ConfigurationProperties
                .getSystemProperty(BaukEngineConfigurationConstants.DETECT_OTHER_BAUK_INSTANCES, false);
        if (detectBaukInstances) {
            final int numberOfInstances = HazelcastCacheInstanceManager.getNumberOfBaukInstances();
            BaukUtil.logEngineMessage(
                    "Total number of detected running engine instances is " + numberOfInstances);
        }
        BaukUtil.logEngineMessage("Engine started successfully in " + total + "ms (" + totalSec
                + " seconds). Waiting for feed files...\n\n");
    } else {
        LOG.error(
                "Unable to find valid configuration file! Check your startup scripts and make sure system property {} points to valid feed configuration file. Aborting!",
                CONFIG_FILE_PROP_NAME);
        BaukUtil.logEngineMessage(
                "Unable to find valid configuration file! Check your startup scripts and make sure system property "
                        + CONFIG_FILE_PROP_NAME + " points to valid feed configuration file. Aborting!");
        System.exit(-1);
    }
    // sleep forever
    while (!BaukUtil.shutdownStarted()) {
        Thread.sleep(10000);
    }
}

From source file:edu.usc.squash.Main.java

public static void main(String[] args) {
    Stack<Module> modulesStack;
    Module module;//  w  ww. j  a va  2  s  .c o m

    if (parseInputs(args) == false) {
        System.exit(-1); //The input files do not exist
    }

    String separator = "----------------------------------------------";
    System.out.println("Squash v2.0");
    System.out.println(separator);
    long start = System.currentTimeMillis();

    // Parsing the input library
    Library library = QLib.readLib(libraryPath);
    library.setCurrentECC(currentECC);

    HashMap<String, Module> modules = parseQASMHF(library);
    Module mainModule = modules.get("main");

    //Finding max{A_L_i}
    int childModulesLogicalAncillaReq;
    int moduleAncillaReq;

    modulesStack = new Stack<Module>();

    modulesStack.add(mainModule);
    while (!modulesStack.isEmpty()) {
        module = modulesStack.peek();
        if (!module.isVisited() && module.isChildrenVisited()) {
            //Finding the maximum 
            childModulesLogicalAncillaReq = 0;
            for (Module child : module.getDFG().getModules()) {
                childModulesLogicalAncillaReq = Math.max(childModulesLogicalAncillaReq, child.getAncillaReq());
            }
            moduleAncillaReq = module.getAncillaQubitNo() + childModulesLogicalAncillaReq;
            module.setAncillaReq(moduleAncillaReq);
            //            System.out.println("Module "+module.getName()+" requires "+moduleAncillaReq+" ancilla.");

            modulesStack.pop();
            module.setVisited();
        } else if (module.isVisited()) {
            modulesStack.pop();
        } else if (!module.isChildrenVisited()) {
            modulesStack.addAll(module.getDFG().getModules());
            module.setChildrenVisited();
        }
    }

    int totalLogicalAncilla = mainModule.getAncillaReq();

    System.out.println("A_L_i_max: " + totalLogicalAncilla);

    final int Q_L = mainModule.getDataQubitNo();

    /* 
     * In order traversal of modules
     */
    //Making sure all of the modules are unvisited
    for (Module m : modules.values()) {
        m.setUnvisited();
    }
    modulesStack = new Stack<Module>();

    modulesStack.add(mainModule);
    while (!modulesStack.isEmpty()) {
        module = modulesStack.peek();
        if (!module.isVisited() && module.isChildrenVisited()) {
            System.out.println(separator);

            mapModule(module, k, physicalAncillaBudget, totalLogicalAncilla, Q_L, beta_pmd, alpha_int,
                    gamma_memory, library);

            modulesStack.pop();
            module.setVisited();
        } else if (module.isVisited()) {
            modulesStack.pop();
        } else if (!module.isChildrenVisited()) {
            modulesStack.addAll(module.getDFG().getModules());
            module.setChildrenVisited();
        }
    }

    System.out.println(separator);
    double runtime = (System.currentTimeMillis() - start) / 1000.0;
    System.out.println("B_P: " + B_P);
    System.out.println("Total Runtime:\t" + runtime + " sec");
}

From source file:com.senseidb.search.node.inmemory.InMemoryIndexPerfEval.java

public static void main(String[] args) throws Exception {
    final InMemorySenseiService memorySenseiService = InMemorySenseiService.valueOf(
            new File(InMemoryIndexPerfEval.class.getClassLoader().getResource("test-conf/node1/").toURI()));

    final List<JSONObject> docs = new ArrayList<JSONObject>(15000);
    LineIterator lineIterator = FileUtils.lineIterator(
            new File(InMemoryIndexPerfEval.class.getClassLoader().getResource("data/test_data.json").toURI()));
    int i = 0;//from   w  w w .  j  a v  a2s .  c  o m
    while (lineIterator.hasNext() && i < 100) {
        String car = lineIterator.next();
        if (car != null && car.contains("{"))
            docs.add(new JSONObject(car));
        i++;
    }
    Thread[] threads = new Thread[10];
    for (int k = 0; k < threads.length; k++) {
        threads[k] = new Thread(new Runnable() {
            public void run() {
                long time = System.currentTimeMillis();
                //System.out.println("Start thread");
                for (int j = 0; j < 1000; j++) {
                    //System.out.println("Send request");
                    memorySenseiService.doQuery(getRequest(), docs);
                }
                System.out.println("time = " + (System.currentTimeMillis() - time));
            }
        });
        threads[k].start();
    }
    Thread.sleep(500000);
}

From source file:com.sm.test.TestConnect.java

public static void main(String[] args) throws Exception {
    String[] opts = new String[] { "-host", "-port", "-times" };
    String[] defaults = new String[] { "ssusd003.ir.dc", "6666", "500" };
    String[] paras = getOpts(args, opts, defaults);
    String host = paras[0];//from   w ww  . j  a  v a 2 s.c  o m
    int port = Integer.valueOf(paras[1]);
    int timeout = Integer.valueOf(paras[2]);

    //        logger.info("pos="+"/test/".indexOf("/"));
    //        logger.info("/test/".substring(0, "/test/".indexOf("/")));
    //        BuildClusterNodes bc = new BuildClusterNodes("./clusterStore/src/test/resources/config.xml");
    //        logger.info(bc.build().toString());
    //        BuildStoreConfig bs = new BuildStoreConfig("./clusterStore/src/test/resources/config.xml");
    //        logger.info(bs.build().toString());
    long begin = System.currentTimeMillis();
    SocketAddress inet = new InetSocketAddress(host, port);
    try {

        Socket socket = new Socket();
        socket.connect(inet, timeout);
        socket.close();
    } catch (Exception ex) {
        logger.error("ex " + ex.toString());
    }
    logger.info("time in Socket ms " + (System.currentTimeMillis() - begin));
    //        begin = System.currentTimeMillis();
    //        try {
    //            TCPClient client = TCPClient.start(host, port);
    //            client.close();
    //        } catch (Exception ex) {
    //            logger.error( ex.getMessage());
    //        }
    //        logger.info("time in TCPClient ms "+(System.currentTimeMillis() - begin));

}

From source file:de.mirkosertic.invertedindex.core.FullIndexRun.java

public static void main(String[] args) throws IOException {
    InvertedIndex theIndex = new InvertedIndex();
    UpdateIndexHandler theIndexHandler = new UpdateIndexHandler(theIndex);
    Tokenizer theTokenizer = new Tokenizer(new ToLowercaseTokenHandler(theIndexHandler));

    File theOrigin = new File("/home/sertic/ownCloud/Textcontent");
    for (File theFile : theOrigin.listFiles()) {
        System.out.println("Indexing " + theFile);
        String theFileContent = IOUtils.toString(new FileReader(theFile));
        theTokenizer.process(new Document(theFile.getName(), theFileContent));
    }//from  ww  w. j a  v  a2 s .  c  om

    System.out.println(theIndex.getTokenCount() + " unique postings");
    System.out.println(theIndex.getDocumentCount() + " documents");

    theIndex.postings.entrySet().stream()
            .sorted((o1, o2) -> ((Integer) o1.getValue().getOccoursInDocuments().size())
                    .compareTo(o2.getValue().getOccoursInDocuments().size()))
            .forEach(t -> {
                System.out.println(t.getKey() + " -> " + t.getValue().getOccoursInDocuments().size());
            });

    System.out.println("Query");

    Result theResult = theIndex.query(new TokenSequenceQuery(new String[] { "introduction", "to", "aop" }));
    System.out.println(theResult.getSize());
    for (int i = 0; i < theResult.getSize(); i++) {
        System.out.println(theResult.getDoc(i).getName());

        System.out.println(theIndex.rebuildContentFor(theResult.getDoc(i)));
    }

    long theCount = 100000;
    long theStart = System.currentTimeMillis();
    for (int i = 0; i < theCount; i++) {
        theResult = theIndex.query(new TokenSequenceQuery(new String[] { "introduction", "to", "aop" }));
    }
    double theDuration = System.currentTimeMillis() - theStart;

    System.out.println(theCount + " Queries took " + theDuration + "ms");
    System.out.println(theDuration / theCount);

    while (true) {
        theResult = theIndex.query(new TokenSequenceQuery(new String[] { "introduction", "to", "aop" }));
    }
}

From source file:com.knewton.mapreduce.example.SSTableMRExample.java

public static void main(String[] args)
        throws IOException, InterruptedException, ClassNotFoundException, URISyntaxException, ParseException {

    long startTime = System.currentTimeMillis();
    Options options = buildOptions();/*from  www.  ja  va 2s .c o m*/

    CommandLineParser cliParser = new BasicParser();
    CommandLine cli = cliParser.parse(options, args);
    if (cli.getArgs().length < 2 || cli.hasOption('h')) {
        printUsage(options);
    }
    Job job = getJobConf(cli);

    job.setJarByClass(SSTableMRExample.class);
    job.setOutputKeyClass(LongWritable.class);
    job.setOutputValueClass(StudentEventWritable.class);

    job.setMapperClass(StudentEventMapper.class);
    job.setReducerClass(StudentEventReducer.class);

    job.setInputFormatClass(SSTableColumnInputFormat.class);
    job.setOutputFormatClass(TextOutputFormat.class);
    // input arg
    String inputPaths = cli.getArgs()[0];
    LOG.info("Setting initial input paths to {}", inputPaths);
    SSTableInputFormat.addInputPaths(job, inputPaths);
    // output arg
    FileOutputFormat.setOutputPath(job, new Path(cli.getArgs()[1]));
    if (cli.hasOption('c')) {
        LOG.info("Using compression for output.");
        FileOutputFormat.setOutputCompressorClass(job, GzipCodec.class);
        FileOutputFormat.setCompressOutput(job, true);
    }
    job.waitForCompletion(true);
    LOG.info("Total runtime: {}s", (System.currentTimeMillis() - startTime) / 1000);
}