Example usage for java.util.concurrent TimeUnit NANOSECONDS

List of usage examples for java.util.concurrent TimeUnit NANOSECONDS

Introduction

In this page you can find the example usage for java.util.concurrent TimeUnit NANOSECONDS.

Prototype

TimeUnit NANOSECONDS

To view the source code for java.util.concurrent TimeUnit NANOSECONDS.

Click Source Link

Document

Time unit representing one thousandth of a microsecond.

Usage

From source file:net.openhft.chronicle.wire.benchmarks.ComparisonMain.java

public static void main(String... args) throws Exception {
    Affinity.setAffinity(2);/*from w  ww  . j a va  2 s. co  m*/
    if (Jvm.isDebug()) {
        ComparisonMain main = new ComparisonMain();
        for (Method m : ComparisonMain.class.getMethods()) {
            main.s = null;
            main.sb.setLength(0);
            main.mhe.wrap(main.directBuffer, 0).blockLength(0);
            main.buf = null;

            if (m.getAnnotation(Benchmark.class) != null) {
                m.invoke(main);
                String s = main.s;
                if (s != null) {
                    System.out.println("Test " + m.getName() + " used " + s.length() + " chars.");
                    System.out.println(s);
                } else if (main.sb.length() > 0) {
                    System.out.println("Test " + m.getName() + " used " + main.sb.length() + " chars.");
                    System.out.println(main.sb);
                } else if (main.mhd.wrap(main.directBuffer, 0).blockLength() > 0) {
                    int len = main.mhd.wrap(main.directBuffer, 0).blockLength() + main.mhd.encodedLength();
                    System.out.println("Test " + m.getName() + " used " + len + " chars.");
                    System.out.println(new NativeBytesStore<>(main.directBuffer.addressOffset(), len)
                            .bytesForRead().toHexString());
                } else if (main.buf != null) {
                    System.out.println("Test " + m.getName() + " used " + main.buf.length + " chars.");
                    System.out.println(Bytes.wrapForRead(main.buf).toHexString());
                } else if (main.bytes.writePosition() > 0) {
                    main.bytes.readPosition(0);
                    System.out
                            .println("Test " + m.getName() + " used " + main.bytes.readRemaining() + " chars.");
                    System.out.println(main.bytes.toHexString());
                }
            }
        }
    } else {
        int time = Boolean.getBoolean("longTest") ? 30 : 2;
        System.out.println("measurementTime: " + time + " secs");
        Options opt = new OptionsBuilder().include(ComparisonMain.class.getSimpleName())
                //                    .warmupIterations(5)
                .measurementIterations(5).forks(10).mode(Mode.SampleTime)
                .measurementTime(TimeValue.seconds(time)).timeUnit(TimeUnit.NANOSECONDS).build();

        new Runner(opt).run();
    }
}

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.
 *//*from   ww  w  .  j a v  a2  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:Main.java

public static String printTime(long time, TimeUnit unit) {
    long ns = TimeUnit.NANOSECONDS.convert(time, unit);
    long us = TimeUnit.MICROSECONDS.convert(time, unit);
    long ms = TimeUnit.MILLISECONDS.convert(time, unit);
    long secs = TimeUnit.SECONDS.convert(time, unit);

    if (secs > 0)
        return secs + "s";
    if (ms > 0)
        return ms + "ms";
    if (us > 0)
        return us + " us";
    return ns + "ns";
}

From source file:Main.java

public static long millitime() {
    return TimeUnit.MILLISECONDS.convert(System.nanoTime(), TimeUnit.NANOSECONDS);
}

From source file:co.paralleluniverse.photon.Photon.java

public static void main(final String[] args) throws InterruptedException, IOException {

    final Options options = new Options();
    options.addOption("rate", true, "Requests per second (default " + rateDefault + ")");
    options.addOption("duration", true,
            "Minimum test duration in seconds: will wait for <duration> * <rate> requests to terminate or, if progress check enabled, no progress after <duration> (default "
                    + durationDefault + ")");
    options.addOption("maxconnections", true,
            "Maximum number of open connections (default " + maxConnectionsDefault + ")");
    options.addOption("timeout", true,
            "Connection and read timeout in millis (default " + timeoutDefault + ")");
    options.addOption("print", true,
            "Print cycle in millis, 0 to disable intermediate statistics (default " + printCycleDefault + ")");
    options.addOption("check", true,
            "Progress check cycle in millis, 0 to disable progress check (default " + checkCycleDefault + ")");
    options.addOption("stats", false, "Print full statistics when finish (default false)");
    options.addOption("minmax", false, "Print min/mean/stddev/max stats when finish (default false)");
    options.addOption("name", true, "Test name to print in the statistics (default '" + testNameDefault + "')");
    options.addOption("help", false, "Print help");

    try {/*from   w  w w. ja v  a 2s.c om*/
        final CommandLine cmd = new BasicParser().parse(options, args);
        final String[] ar = cmd.getArgs();
        if (cmd.hasOption("help") || ar.length != 1)
            printUsageAndExit(options);

        final String url = ar[0];

        final int timeout = Integer.parseInt(cmd.getOptionValue("timeout", timeoutDefault));
        final int maxConnections = Integer
                .parseInt(cmd.getOptionValue("maxconnections", maxConnectionsDefault));
        final int duration = Integer.parseInt(cmd.getOptionValue("duration", durationDefault));
        final int printCycle = Integer.parseInt(cmd.getOptionValue("print", printCycleDefault));
        final int checkCycle = Integer.parseInt(cmd.getOptionValue("check", checkCycleDefault));
        final String testName = cmd.getOptionValue("name", testNameDefault);
        final int rate = Integer.parseInt(cmd.getOptionValue("rate", rateDefault));

        final MetricRegistry metrics = new MetricRegistry();
        final Meter requestMeter = metrics.meter("request");
        final Meter responseMeter = metrics.meter("response");
        final Meter errorsMeter = metrics.meter("errors");
        final Logger log = LoggerFactory.getLogger(Photon.class);
        final ConcurrentHashMap<String, AtomicInteger> errors = new ConcurrentHashMap<>();
        final HttpGet request = new HttpGet(url);
        final StripedTimeSeries<Long> sts = new StripedTimeSeries<>(30000, false);
        final StripedHistogram sh = new StripedHistogram(60000, 5);

        log.info("name: " + testName + " url:" + url + " rate:" + rate + " duration:" + duration
                + " maxconnections:" + maxConnections + ", " + "timeout:" + timeout);
        final DefaultConnectingIOReactor ioreactor = new DefaultConnectingIOReactor(IOReactorConfig.custom()
                .setConnectTimeout(timeout).setIoThreadCount(10).setSoTimeout(timeout).build());

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            final List<ExceptionEvent> events = ioreactor.getAuditLog();
            if (events != null)
                events.stream().filter(event -> event != null).forEach(event -> {
                    System.err.println(
                            "Apache Async HTTP Client I/O Reactor Error Time: " + event.getTimestamp());
                    //noinspection ThrowableResultOfMethodCallIgnored
                    if (event.getCause() != null)
                        //noinspection ThrowableResultOfMethodCallIgnored
                        event.getCause().printStackTrace();
                });
            if (cmd.hasOption("stats"))
                printFinishStatistics(errorsMeter, sts, sh, testName);
            if (!errors.keySet().isEmpty())
                errors.entrySet().stream()
                        .forEach(p -> log.info(testName + " " + p.getKey() + " " + p.getValue() + "ms"));
            System.out.println(
                    testName + " responseTime(90%): " + sh.getHistogramData().getValueAtPercentile(90) + "ms");
            if (cmd.hasOption("minmax")) {
                final HistogramData hd = sh.getHistogramData();
                System.out.format("%s %8s%8s%8s%8s\n", testName, "min", "mean", "sd", "max");
                System.out.format("%s %8d%8.2f%8.2f%8d\n", testName, hd.getMinValue(), hd.getMean(),
                        hd.getStdDeviation(), hd.getMaxValue());
            }
        }));

        final PoolingNHttpClientConnectionManager mngr = new PoolingNHttpClientConnectionManager(ioreactor);
        mngr.setDefaultMaxPerRoute(maxConnections);
        mngr.setMaxTotal(maxConnections);
        final CloseableHttpAsyncClient ahc = HttpAsyncClientBuilder.create().setConnectionManager(mngr)
                .setDefaultRequestConfig(RequestConfig.custom().setLocalAddress(null).build()).build();
        try (final CloseableHttpClient client = new FiberHttpClient(ahc)) {
            final int num = duration * rate;

            final CountDownLatch cdl = new CountDownLatch(num);
            final Semaphore sem = new Semaphore(maxConnections);
            final RateLimiter rl = RateLimiter.create(rate);

            spawnStatisticsThread(printCycle, cdl, log, requestMeter, responseMeter, errorsMeter, testName);

            for (int i = 0; i < num; i++) {
                rl.acquire();
                if (sem.availablePermits() == 0)
                    log.debug("Maximum connections count reached, waiting...");
                sem.acquireUninterruptibly();

                new Fiber<Void>(() -> {
                    requestMeter.mark();
                    final long start = System.nanoTime();
                    try {
                        try (final CloseableHttpResponse ignored = client.execute(request)) {
                            responseMeter.mark();
                        } catch (final Throwable t) {
                            markError(errorsMeter, errors, t);
                        }
                    } catch (final Throwable t) {
                        markError(errorsMeter, errors, t);
                    } finally {
                        final long now = System.nanoTime();
                        final long millis = TimeUnit.NANOSECONDS.toMillis(now - start);
                        sts.record(start, millis);
                        sh.recordValue(millis);
                        sem.release();
                        cdl.countDown();
                    }
                }).start();
            }
            spawnProgressCheckThread(log, duration, checkCycle, cdl);
            cdl.await();
        }
    } catch (final ParseException ex) {
        System.err.println("Parsing failed.  Reason: " + ex.getMessage());
    }
}

From source file:Main.java

static void awaitTermination(ExecutorService threadPool) {
    threadPool.shutdown();//  w w  w  . ja  v  a  2  s .  co  m
    try {
        threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:io.anserini.search.SearchWebCollection.java

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

    SearchArgs searchArgs = new SearchArgs();
    CmdLineParser parser = new CmdLineParser(searchArgs, ParserProperties.defaults().withUsageWidth(90));

    try {//from  w  w  w.  ja  v a2 s. co m
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        parser.printUsage(System.err);
        System.err.println("Example: SearchWebCollection" + parser.printExample(OptionHandlerFilter.REQUIRED));
        return;
    }

    LOG.info("Reading index at " + searchArgs.index);
    Directory dir;
    if (searchArgs.inmem) {
        LOG.info("Using MMapDirectory with preload");
        dir = new MMapDirectory(Paths.get(searchArgs.index));
        ((MMapDirectory) dir).setPreload(true);
    } else {
        LOG.info("Using default FSDirectory");
        dir = FSDirectory.open(Paths.get(searchArgs.index));
    }

    Similarity similarity = null;

    if (searchArgs.ql) {
        LOG.info("Using QL scoring model");
        similarity = new LMDirichletSimilarity(searchArgs.mu);
    } else if (searchArgs.bm25) {
        LOG.info("Using BM25 scoring model");
        similarity = new BM25Similarity(searchArgs.k1, searchArgs.b);
    } else {
        LOG.error("Error: Must specify scoring model!");
        System.exit(-1);
    }

    RerankerCascade cascade = new RerankerCascade();
    boolean useQueryParser = false;
    if (searchArgs.rm3) {
        cascade.add(new Rm3Reranker(new EnglishAnalyzer(), FIELD_BODY,
                "src/main/resources/io/anserini/rerank/rm3/rm3-stoplist.gov2.txt"));
        useQueryParser = true;
    } else {
        cascade.add(new IdentityReranker());
    }
    FeatureExtractors extractors = null;
    if (searchArgs.extractors != null) {
        extractors = FeatureExtractors.loadExtractor(searchArgs.extractors);
    }

    if (searchArgs.dumpFeatures) {
        PrintStream out = new PrintStream(searchArgs.featureFile);
        Qrels qrels = new Qrels(searchArgs.qrels);
        cascade.add(new WebCollectionLtrDataGenerator(out, qrels, extractors));
    }

    Path topicsFile = Paths.get(searchArgs.topics);

    if (!Files.exists(topicsFile) || !Files.isRegularFile(topicsFile) || !Files.isReadable(topicsFile)) {
        throw new IllegalArgumentException(
                "Topics file : " + topicsFile + " does not exist or is not a (readable) file.");
    }

    TopicReader tr = (TopicReader) Class
            .forName("io.anserini.search.query." + searchArgs.topicReader + "TopicReader")
            .getConstructor(Path.class).newInstance(topicsFile);
    SortedMap<Integer, String> topics = tr.read();

    final long start = System.nanoTime();
    SearchWebCollection searcher = new SearchWebCollection(searchArgs.index);
    searcher.search(topics, searchArgs.output, similarity, searchArgs.hits, cascade, useQueryParser,
            searchArgs.keepstop);
    searcher.close();
    final long durationMillis = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS);
    LOG.info("Total " + topics.size() + " topics searched in "
            + DurationFormatUtils.formatDuration(durationMillis, "HH:mm:ss"));
}

From source file:Main.java

/**
 * sleep until timeout./*  w  w  w. ja  v a2  s . c  om*/
 * 
 * @param nanos
 */
public final static void deepSleep(long sleepFor, TimeUnit unit) {
    if (sleepFor < 0) {
        throw new IllegalArgumentException("sleepFor can't be minus.");
    }
    long startTimeInNanos = System.nanoTime();
    long leftNanos = unit.toNanos(sleepFor);
    boolean isInterrupted = false;
    while (leftNanos > 0) {
        try {
            TimeUnit.NANOSECONDS.sleep(leftNanos);
            leftNanos = 0;
        } catch (InterruptedException e) {
            isInterrupted = true;
            leftNanos -= (System.nanoTime() - startTimeInNanos);
        }
    }

    if (isInterrupted) {
        Thread.currentThread().interrupt();
    }
}

From source file:Main.java

public static TimeUnit convert(ChronoUnit tu) {
    if (tu == null) {
        return null;
    }/*from  ww  w . ja v a2  s.c  om*/
    switch (tu) {
    case DAYS:
        return TimeUnit.DAYS;
    case HOURS:
        return TimeUnit.HOURS;
    case MINUTES:
        return TimeUnit.MINUTES;
    case SECONDS:
        return TimeUnit.SECONDS;
    case MICROS:
        return TimeUnit.MICROSECONDS;
    case MILLIS:
        return TimeUnit.MILLISECONDS;
    case NANOS:
        return TimeUnit.NANOSECONDS;
    default:
        //TODO support the rest
        throw new UnsupportedOperationException("Man, use a real temporal unit");
    }
}

From source file:Main.java

public static final void sleep(long pTime, TimeUnit pTimeUnit) {
    final long lStart = System.nanoTime();
    long lDeadlineInNanos = lStart + pTimeUnit.toNanos(pTime);

    boolean lSleepTimeBelowMillisecond = pTimeUnit.toMillis(pTime) == 0;

    long lNanoTime;
    while ((lNanoTime = System.nanoTime()) < lDeadlineInNanos) {

        try {// www . ja v  a  2s . c  om
            if (lSleepTimeBelowMillisecond) {
                long lTimeToWaitInNanos = 3 * (lDeadlineInNanos - lNanoTime) / 4;
                if (lTimeToWaitInNanos > 0)
                    Thread.sleep(0, (int) lTimeToWaitInNanos);
            } else {
                long lTimeToWaitInNanos = 3 * (lDeadlineInNanos - lNanoTime) / 4;
                if (lTimeToWaitInNanos > 0) {
                    long lTimeToWaitInMillis = TimeUnit.NANOSECONDS.toMillis(lTimeToWaitInNanos);

                    Thread.sleep(lTimeToWaitInMillis, (int) (lTimeToWaitInNanos % 1000000L));
                }
            }
        } catch (InterruptedException e) {
        }
    }
}