Example usage for java.lang System nanoTime

List of usage examples for java.lang System nanoTime

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public static native long nanoTime();

Source Link

Document

Returns the current value of the running Java Virtual Machine's high-resolution time source, in nanoseconds.

Usage

From source file:com.ibm.bi.dml.runtime.controlprogram.parfor.RemoteParForSpark.java

/**
 * /*w w  w. j a v a2s.  c  o  m*/
 * @param pfid
 * @param program
 * @param tasks
 * @param ec
 * @param enableCPCaching
 * @param numMappers
 * @return
 * @throws DMLRuntimeException 
 * @throws DMLUnsupportedOperationException 
 */
public static RemoteParForJobReturn runJob(long pfid, String program, List<Task> tasks, ExecutionContext ec,
        boolean cpCaching, int numMappers) throws DMLRuntimeException, DMLUnsupportedOperationException {
    String jobname = "ParFor-ESP";
    long t0 = DMLScript.STATISTICS ? System.nanoTime() : 0;

    SparkExecutionContext sec = (SparkExecutionContext) ec;
    JavaSparkContext sc = sec.getSparkContext();

    //initialize accumulators for tasks/iterations
    Accumulator<Integer> aTasks = sc.accumulator(0);
    Accumulator<Integer> aIters = sc.accumulator(0);

    //run remote_spark parfor job 
    //(w/o lazy evaluation to fit existing parfor framework, e.g., result merge)
    RemoteParForSparkWorker func = new RemoteParForSparkWorker(program, cpCaching, aTasks, aIters);
    List<Tuple2<Long, String>> out = sc.parallelize(tasks, numMappers) //create rdd of parfor tasks
            .flatMapToPair(func) //execute parfor tasks 
            .collect(); //get output handles

    //de-serialize results
    LocalVariableMap[] results = RemoteParForUtils.getResults(out, LOG);
    int numTasks = aTasks.value(); //get accumulator value
    int numIters = aIters.value(); //get accumulator value

    //create output symbol table entries
    RemoteParForJobReturn ret = new RemoteParForJobReturn(true, numTasks, numIters, results);

    //maintain statistics
    Statistics.incrementNoOfCompiledSPInst();
    Statistics.incrementNoOfExecutedSPInst();
    if (DMLScript.STATISTICS) {
        Statistics.maintainCPHeavyHitters(jobname, System.nanoTime() - t0);
    }

    return ret;
}

From source file:io.kahu.hawaii.util.call.statistics.RequestStatistic.java

public void endCallback() {
    this.endCallbackNano = System.nanoTime();
}

From source file:org.apache.hadoop.gateway.dispatch.KnoxSpnegoAuthScheme.java

@Override
protected byte[] generateToken(final byte[] input, final String authServer) throws GSSException {
    // This is done to avoid issues with Keberos service ticket replay detection on the service side.
    synchronized (KnoxSpnegoAuthScheme.class) {
        long now;
        // This just insures that the system clock has advanced to a different nanosecond.
        // Kerberos uses microsecond resolution and 1ms=1000ns.
        while ((now = System.nanoTime()) == nano) {
            try {
                Thread.sleep(0);// w w  w . jav a  2 s.  c  o  m
            } catch (InterruptedException e) {
                // Ignore it.
            }
        }
        nano = now;
        return super.generateToken(input, authServer);
    }
}

From source file:de.tynne.benchmarksuite.Main.java

private static void nanoNullLoop(int times, List<Long> addTo) {
    for (int i = 0; i < times; i++) {
        long start = System.nanoTime();
        long end = System.nanoTime();

        long diff = end - start;
        addTo.add(diff);/*from   w w  w  .j  a v  a  2 s .  c o  m*/
    }
}

From source file:com.joyent.manta.http.DynamicHttpSignatureRequestInterceptor.java

@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    if (authConfig.noAuth()) {
        return;/*from   w  ww.  j  ava2  s . com*/
    }

    final long start = System.nanoTime();
    final HttpSignatureAuthScheme authScheme = authConfig.getAuthScheme();
    final Header authorization = authScheme.authenticate(authConfig.getCredentials(), request, context);
    final long end = System.nanoTime();

    request.setHeader(authorization);
    request.setHeader("x-http-signing-time-ns", String.valueOf(end - start));
}

From source file:eu.planets_project.pp.plato.services.characterisation.jhove.JHoveAdaptor.java

public String describe(DigitalObject object) {
    try {//from   ww  w .  java 2s  .c o  m
        if (object.isDataExistent()) {
            return jHove.getJHoveInfoAsString(object.getId() + System.nanoTime() + "",
                    object.getData().getData());
        } else {
            return "";
        }
    } catch (Exception ex) {
        log.error("Cannot initialize jhove XML String" + ex.getMessage(), ex);
        return null;
    }
}

From source file:org.elasticsearch.xpack.watcher.common.http.HttpConnectionTimeoutTests.java

@Network
public void testDefaultTimeout() throws Exception {
    Environment environment = TestEnvironment
            .newEnvironment(Settings.builder().put("path.home", createTempDir()).build());
    HttpClient httpClient = new HttpClient(Settings.EMPTY, mock(HttpAuthRegistry.class),
            new SSLService(environment.settings(), environment));

    HttpRequest request = HttpRequest.builder(UNROUTABLE_IP, 12345).method(HttpMethod.POST)
            .path("/" + randomAlphaOfLength(5)).build();

    long start = System.nanoTime();
    try {/*from w  w w  . j  a  va 2 s.c  o  m*/
        httpClient.execute(request);
        fail("expected timeout exception");
    } catch (ConnectTimeoutException ete) {
        TimeValue timeout = TimeValue.timeValueNanos(System.nanoTime() - start);
        logger.info("http connection timed out after {}", timeout);
        // it's supposed to be 10, but we'll give it an error margin of 2 seconds
        assertThat(timeout.seconds(), greaterThan(8L));
        assertThat(timeout.seconds(), lessThan(12L));
        // expected
    }
}

From source file:Main.java

/**
 * Get the expected value of {@link System#nanoTime} after the given period has passed.  Negative values
 * for {@code time} return a time from the past.  Note that, since an overflow wrap-around may occur
 * at any time in the system's nanosecond clock, comparisons between the current time and this method's
 * result are non-trivial.  For example, to test whether the result time {@code future} has passed:
 * {@code System.nanoTime() - future > 0}.  (This checks that the current time is within a Long.MAX_VALUE range
 * <em>after</em> {@code future}, regardless of the absolute numeric values.  We can infer that (most likely)
 * {@code future} is less than 292 years in the past, or (unlikely) future is more than 292 years in the future.)
 */// w ww . j  ava 2  s.  c o  m
public static long futureTimeNanos(long time, TimeUnit unit) {
    return System.nanoTime() + unit.toNanos(time);
}

From source file:com.conwet.silbops.model.JSONvsRMIPerfT.java

public static void externalizeSeveralObjects(Externalizable[] objects, ByteArrayOutputStream baos) {

    long start = 0, end = 0;

    try {// ww w .j  a va 2 s.  com
        ObjectOutputStream out = new ObjectOutputStream(baos);

        //Measure the elapsed time
        start = System.nanoTime();

        for (Externalizable object : objects) {
            out.writeObject(object);
        }

        end = System.nanoTime();

        out.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    long elapsed = (end - start);
    long elapsedPerMessage = elapsed / objects.length;
    System.out.println("   Elapsed Time " + objects.length + " messages - Externalize: " + elapsed
            + " nanoseconds (" + elapsedPerMessage + " nanoseconds/msg)");
}

From source file:com.yahoo.pulsar.testclient.PerformanceProducer.java

public static void main(String[] args) throws Exception {
    final Arguments arguments = new Arguments();
    JCommander jc = new JCommander(arguments);
    jc.setProgramName("pulsar-perf-producer");

    try {//from  w ww.  j  a v a2 s . co  m
        jc.parse(args);
    } catch (ParameterException e) {
        System.out.println(e.getMessage());
        jc.usage();
        System.exit(-1);
    }

    if (arguments.help) {
        jc.usage();
        System.exit(-1);
    }

    if (arguments.destinations.size() != 1) {
        System.out.println("Only one topic name is allowed");
        jc.usage();
        System.exit(-1);
    }

    if (arguments.confFile != null) {
        Properties prop = new Properties(System.getProperties());
        prop.load(new FileInputStream(arguments.confFile));

        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("brokerServiceUrl");
        }

        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("webServiceUrl");
        }

        // fallback to previous-version serviceUrl property to maintain backward-compatibility
        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("serviceUrl", "http://localhost:8080/");
        }

        if (arguments.authPluginClassName == null) {
            arguments.authPluginClassName = prop.getProperty("authPlugin", null);
        }

        if (arguments.authParams == null) {
            arguments.authParams = prop.getProperty("authParams", null);
        }
    }

    arguments.testTime = TimeUnit.SECONDS.toMillis(arguments.testTime);

    // Dump config variables
    ObjectMapper m = new ObjectMapper();
    ObjectWriter w = m.writerWithDefaultPrettyPrinter();
    log.info("Starting Pulsar perf producer with config: {}", w.writeValueAsString(arguments));

    // Read payload data from file if needed
    byte payloadData[];
    if (arguments.payloadFilename != null) {
        payloadData = Files.readAllBytes(Paths.get(arguments.payloadFilename));
    } else {
        payloadData = new byte[arguments.msgSize];
    }

    // Now processing command line arguments
    String prefixTopicName = arguments.destinations.get(0);
    List<Future<Producer>> futures = Lists.newArrayList();

    EventLoopGroup eventLoopGroup;
    if (SystemUtils.IS_OS_LINUX) {
        eventLoopGroup = new EpollEventLoopGroup(Runtime.getRuntime().availableProcessors(),
                new DefaultThreadFactory("pulsar-perf-producer"));
    } else {
        eventLoopGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors(),
                new DefaultThreadFactory("pulsar-perf-producer"));
    }

    ClientConfiguration clientConf = new ClientConfiguration();
    clientConf.setConnectionsPerBroker(arguments.maxConnections);
    clientConf.setStatsInterval(arguments.statsIntervalSeconds, TimeUnit.SECONDS);
    if (isNotBlank(arguments.authPluginClassName)) {
        clientConf.setAuthentication(arguments.authPluginClassName, arguments.authParams);
    }

    PulsarClient client = new PulsarClientImpl(arguments.serviceURL, clientConf, eventLoopGroup);

    ProducerConfiguration producerConf = new ProducerConfiguration();
    producerConf.setSendTimeout(0, TimeUnit.SECONDS);
    producerConf.setCompressionType(arguments.compression);
    // enable round robin message routing if it is a partitioned topic
    producerConf.setMessageRoutingMode(MessageRoutingMode.RoundRobinPartition);
    if (arguments.batchTime > 0) {
        producerConf.setBatchingMaxPublishDelay(arguments.batchTime, TimeUnit.MILLISECONDS);
        producerConf.setBatchingEnabled(true);
        producerConf.setMaxPendingMessages(arguments.msgRate);
    }

    for (int i = 0; i < arguments.numTopics; i++) {
        String topic = (arguments.numTopics == 1) ? prefixTopicName
                : String.format("%s-%d", prefixTopicName, i);
        log.info("Adding {} publishers on destination {}", arguments.numProducers, topic);

        for (int j = 0; j < arguments.numProducers; j++) {
            futures.add(client.createProducerAsync(topic, producerConf));
        }
    }

    final List<Producer> producers = Lists.newArrayListWithCapacity(futures.size());
    for (Future<Producer> future : futures) {
        producers.add(future.get());
    }

    log.info("Created {} producers", producers.size());

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            printAggregatedStats();
        }
    });

    Collections.shuffle(producers);
    AtomicBoolean isDone = new AtomicBoolean();

    executor.submit(() -> {
        try {
            RateLimiter rateLimiter = RateLimiter.create(arguments.msgRate);

            long startTime = System.currentTimeMillis();

            // Send messages on all topics/producers
            long totalSent = 0;
            while (true) {
                for (Producer producer : producers) {
                    if (arguments.testTime > 0) {
                        if (System.currentTimeMillis() - startTime > arguments.testTime) {
                            log.info("------------------- DONE -----------------------");
                            printAggregatedStats();
                            isDone.set(true);
                            Thread.sleep(5000);
                            System.exit(0);
                        }
                    }

                    if (arguments.numMessages > 0) {
                        if (totalSent++ >= arguments.numMessages) {
                            log.info("------------------- DONE -----------------------");
                            printAggregatedStats();
                            isDone.set(true);
                            Thread.sleep(5000);
                            System.exit(0);
                        }
                    }
                    rateLimiter.acquire();

                    final long sendTime = System.nanoTime();

                    producer.sendAsync(payloadData).thenRun(() -> {
                        messagesSent.increment();
                        bytesSent.add(payloadData.length);

                        long latencyMicros = NANOSECONDS.toMicros(System.nanoTime() - sendTime);
                        recorder.recordValue(latencyMicros);
                        cumulativeRecorder.recordValue(latencyMicros);
                    }).exceptionally(ex -> {
                        log.warn("Write error on message", ex);
                        System.exit(-1);
                        return null;
                    });
                }
            }
        } catch (Throwable t) {
            log.error("Got error", t);
        }
    });

    // Print report stats
    long oldTime = System.nanoTime();

    Histogram reportHistogram = null;

    String statsFileName = "perf-producer-" + System.currentTimeMillis() + ".hgrm";
    log.info("Dumping latency stats to {}", statsFileName);

    PrintStream histogramLog = new PrintStream(new FileOutputStream(statsFileName), false);
    HistogramLogWriter histogramLogWriter = new HistogramLogWriter(histogramLog);

    // Some log header bits
    histogramLogWriter.outputLogFormatVersion();
    histogramLogWriter.outputLegend();

    while (true) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            break;
        }

        if (isDone.get()) {
            break;
        }

        long now = System.nanoTime();
        double elapsed = (now - oldTime) / 1e9;

        double rate = messagesSent.sumThenReset() / elapsed;
        double throughput = bytesSent.sumThenReset() / elapsed / 1024 / 1024 * 8;

        reportHistogram = recorder.getIntervalHistogram(reportHistogram);

        log.info(
                "Throughput produced: {}  msg/s --- {} Mbit/s --- Latency: mean: {} ms - med: {} - 95pct: {} - 99pct: {} - 99.9pct: {} - 99.99pct: {} - Max: {}",
                throughputFormat.format(rate), throughputFormat.format(throughput),
                dec.format(reportHistogram.getMean() / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(50) / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(95) / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(99) / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(99.9) / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(99.99) / 1000.0),
                dec.format(reportHistogram.getMaxValue() / 1000.0));

        histogramLogWriter.outputIntervalHistogram(reportHistogram);
        reportHistogram.reset();

        oldTime = now;
    }

    client.close();
}