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.netflix.genie.core.jobs.workflow.impl.JobTask.java

/**
 * {@inheritDoc}// w  w w . j av a  2 s .c  om
 */
@Override
public void executeTask(@NotNull final Map<String, Object> context) throws GenieException, IOException {
    final long start = System.nanoTime();
    try {
        final JobExecutionEnvironment jobExecEnv = (JobExecutionEnvironment) context
                .get(JobConstants.JOB_EXECUTION_ENV_KEY);
        final String jobWorkingDirectory = jobExecEnv.getJobWorkingDir().getCanonicalPath();
        final Writer writer = (Writer) context.get(JobConstants.WRITER_KEY);
        final String jobId = jobExecEnv.getJobRequest().getId()
                .orElseThrow(() -> new GeniePreconditionException("No job id found. Unable to continue"));
        log.info("Starting Job Task for job {}", jobId);

        final Optional<String> setupFile = jobExecEnv.getJobRequest().getSetupFile();
        if (setupFile.isPresent()) {
            final String jobSetupFile = setupFile.get();
            if (StringUtils.isNotBlank(jobSetupFile)) {
                final String localPath = jobWorkingDirectory + JobConstants.FILE_PATH_DELIMITER + jobSetupFile
                        .substring(jobSetupFile.lastIndexOf(JobConstants.FILE_PATH_DELIMITER) + 1);

                fts.getFile(jobSetupFile, localPath);

                writer.write("# Sourcing setup file specified in job request" + System.lineSeparator());
                writer.write(
                        JobConstants.SOURCE
                                + localPath.replace(jobWorkingDirectory,
                                        "${" + JobConstants.GENIE_JOB_DIR_ENV_VAR + "}")
                                + System.lineSeparator());

                // Append new line
                writer.write(System.lineSeparator());
            }
        }

        // Iterate over and get all dependencies
        for (final String dependencyFile : jobExecEnv.getJobRequest().getDependencies()) {
            if (StringUtils.isNotBlank(dependencyFile)) {
                final String localPath = jobWorkingDirectory + JobConstants.FILE_PATH_DELIMITER + dependencyFile
                        .substring(dependencyFile.lastIndexOf(JobConstants.FILE_PATH_DELIMITER) + 1);

                fts.getFile(dependencyFile, localPath);
            }
        }

        // Copy down the attachments if any to the current working directory
        this.attachmentService.copy(jobId, jobExecEnv.getJobWorkingDir());
        // Delete the files from the attachment service to save space on disk
        this.attachmentService.delete(jobId);

        // Print out the current Envrionment to a env file before running the command.
        writer.write("# Dump the environment to a env.log file" + System.lineSeparator());
        writer.write("env | sort > " + "${" + JobConstants.GENIE_JOB_DIR_ENV_VAR + "}"
                + JobConstants.GENIE_ENV_PATH + System.lineSeparator());

        // Append new line
        writer.write(System.lineSeparator());

        writer.write("# Kick off the command in background mode and wait for it using its pid"
                + System.lineSeparator());

        writer.write(jobExecEnv.getCommand().getExecutable() + JobConstants.WHITE_SPACE
                + jobExecEnv.getJobRequest().getCommandArgs() + JobConstants.STDOUT_REDIRECT
                + JobConstants.STDOUT_LOG_FILE_NAME + JobConstants.STDERR_REDIRECT
                + JobConstants.STDERR_LOG_FILE_NAME + " &" + System.lineSeparator());

        // Wait for the above process started in background mode. Wait lets us get interrupted by kill signals.
        writer.write("wait $!" + System.lineSeparator());

        // Append new line
        writer.write(System.lineSeparator());

        // capture exit code and write to genie.done file
        writer.write("# Write the return code from the command in the done file." + System.lineSeparator());
        writer.write(JobConstants.GENIE_DONE_FILE_CONTENT_PREFIX + JobConstants.GENIE_DONE_FILE_NAME
                + System.lineSeparator());

        // Print the timestamp once its done running.
        writer.write("echo End: `date '+%Y-%m-%d %H:%M:%S'`\n");

        log.info("Finished Job Task for job {}", jobExecEnv.getJobRequest().getId());
    } finally {
        final long finish = System.nanoTime();
        this.timer.record(finish - start, TimeUnit.NANOSECONDS);
    }
}

From source file:io.galeb.router.services.JmxReporterService.java

private long extractDelta(final AtomicLong last, final ToLongFunction<Undertow.ListenerInfo> longFunction) {
    long start = System.nanoTime();
    double localLast = last.get() * 1.0;
    double current = undertow.getListenerInfo().stream().mapToLong(longFunction).sum() * 1.0;
    long end = System.nanoTime();
    last.set((long) current);
    return Math.round((current * ((double) end / (double) start)) - localLast);
}

From source file:com.aerospike.examples.ldt.SiteVisitEntry.java

/**
 * Generate a customer record based on the seed value. 
 * @param console//www .  j a  va 2s . c  o  m
 * @param customerBaseSet
 * @param userID
 * @param seed
 * @param ldtBinName
 * @param timeToLive -- time expressed in nanoseconds.
 */
public SiteVisitEntry(Console console, String custID, String userID, int seed, String ldtBinName,
        long timeToLive) {
    this.console = console;
    this.customerBaseSet = custID;
    this.customerCacheSet = custID + ":cache";
    this.userID = userID;

    this.url = String.format("url(%d)", seed);
    this.referrer = String.format("Referrer(%d)", seed);
    this.pageTitle = String.format("PageTitle(%d)", seed);

    this.ldtBinName = ldtBinName;

    // Get the current Time.  However, better to use NANO-seconds rather
    // than milliseconds -- because we get duplicates with milliseconds.
    this.timeToLive = timeToLive;
    this.date = System.nanoTime();
    this.expire = this.date + timeToLive;

    this.index = seed;
}

From source file:com.alibaba.dubbo.rpc.benchmark.AbstractClientRunnable.java

private void runJavaAndHessian() {
    while (running) {
        long beginTime = System.nanoTime() / 1000L;
        if (beginTime >= endTime) {
            running = false;/*from   w w w .j  av a 2 s  .  c  o  m*/
            break;
        }
        try {
            Object result = invoke(serviceFactory);
            long currentTime = System.nanoTime() / 1000L;
            if (beginTime <= startTime) {
                continue;
            }
            long consumeTime = currentTime - beginTime;
            sumResponseTimeSpread(consumeTime);
            int range = Integer.parseInt(String.valueOf(beginTime - startTime)) / 1000000;
            if (range >= maxRange) {
                System.err.println(
                        "benchmark range exceeds maxRange,range is: " + range + ",maxRange is: " + maxRange);
                continue;
            }
            if (result != null) {
                tps[range] = tps[range] + 1;
                responseTimes[range] = responseTimes[range] + consumeTime;
            } else {
                LOGGER.error("server return result is null");
                errorTPS[range] = errorTPS[range] + 1;
                errorResponseTimes[range] = errorResponseTimes[range] + consumeTime;
            }
        } catch (Exception e) {
            LOGGER.error("client.invokeSync error", e);
            long currentTime = System.nanoTime() / 1000L;
            if (beginTime <= startTime) {
                continue;
            }
            long consumeTime = currentTime - beginTime;
            sumResponseTimeSpread(consumeTime);
            int range = Integer.parseInt(String.valueOf(beginTime - startTime)) / 1000000;
            if (range >= maxRange) {
                System.err.println(
                        "benchmark range exceeds maxRange,range is: " + range + ",maxRange is: " + maxRange);
                continue;
            }
            errorTPS[range] = errorTPS[range] + 1;
            errorResponseTimes[range] = errorResponseTimes[range] + consumeTime;
        }
    }
}

From source file:com.devicehive.handler.notification.NotificationInsertHandlerTest.java

@Test
public void testInsertNotification() throws ExecutionException, InterruptedException, TimeoutException {
    final String guid = UUID.randomUUID().toString();
    final long id = System.nanoTime();

    DeviceNotification originalNotification = new DeviceNotification();
    originalNotification.setTimestamp(Date.from(Instant.now()));
    originalNotification.setId(id);//from   w  ww  .j  a va2s.  c  o  m
    originalNotification.setDeviceGuid(guid);
    originalNotification.setNotification("SOME TEST DATA");
    originalNotification.setParameters(new JsonStringWrapper("{\"param1\":\"value1\",\"param2\":\"value2\"}"));
    NotificationInsertRequest nir = new NotificationInsertRequest(originalNotification);
    Response response = handler.handle(Request.newBuilder().withBody(nir).build());

    assertTrue(hazelcastService.find(id, guid, DeviceNotification.class)
            .filter(notification -> notification.equals(originalNotification)).isPresent());

    ArgumentCaptor<NotificationEvent> eventCaptor = ArgumentCaptor.forClass(NotificationEvent.class);
    verify(eventBus).publish(eventCaptor.capture());
    NotificationEvent event = eventCaptor.getValue();
    assertEquals(event.getNotification(), originalNotification);

    assertNotNull(response);
    assertNotNull(response.getBody());
    assertTrue(response.getBody() instanceof NotificationInsertResponse);
    NotificationInsertResponse body = (NotificationInsertResponse) response.getBody();
    assertEquals(body.getDeviceNotification(), originalNotification);
}

From source file:hudson.plugins.testlink.result.ResultSeekerTestCase.java

protected void setUp() throws Exception {
    super.setUp();

    project = createFreeStyleProject();//from  ww  w . j av a2  s . c o m
    File temp = File.createTempFile("resultseeker", Long.toString(System.nanoTime()));

    if (!(temp.delete())) {
        throw new IOException("Could not delete temp directory " + temp);
    }

    if (!(temp.mkdir())) {
        throw new IOException("Could not create temp directory " + temp);
    }

    File workspaceFile = new File(temp, getResultsDirectory());

    if (!(workspaceFile.mkdirs())) {
        throw new IOException("Could not create temp workspace " + temp);
    }

    ClassLoader cl = ResultSeekerTestCase.class.getClassLoader();
    URL url = cl.getResource(getResultsDirectory());
    File junitDir = new File(url.getFile());

    FileUtils.copyDirectory(junitDir, workspaceFile);

    project.setCustomWorkspace(workspaceFile.getAbsolutePath());

    project.getBuildersList()
            .add(new ResultSeekerBuilder(getResultSeeker(), getAutomatedTestCases(), testlink));
}

From source file:org.arrow.data.neo4j.store.impl.ProcessInstanceStoreImpl.java

private Node getProcessInstance() {

    Map<String, Object> properties = new HashMap<>();
    properties.put("id", String.valueOf(System.nanoTime()));

    Node pi = template.createNode(properties);
    pi.addLabel(DynamicLabel.label("ProcessInstance"));
    pi.addLabel(DynamicLabel.label("_ProcessInstance"));

    return pi;//w  w w.j a  v a2 s. c  om
}

From source file:com.alibaba.json.test.JSONParser2Test.java

public void f_ali_json() throws Exception {
    // String input = "[{\"a\":3}]";
    long startNano = System.nanoTime();
    for (int i = 0; i < COUNT; ++i) {
        DefaultJSONParser parser = new DefaultJSONParser(text);
        parser.parse();/*w  ww.java2  s . c om*/
    }
    long nano = System.nanoTime() - startNano;
    System.out.println("fast-json \t: " + NumberFormat.getInstance().format(nano));
}

From source file:com.esri.geoevent.test.tools.RunTcpInTcpOutTest.java

public void send(String server, Integer port, Long numEvents, Integer rate) {
    Random rnd = new Random();
    BufferedReader br = null;//  www.  jav a2 s .c  o m
    LocalDateTime st = null;

    try {
        Socket sckt = new Socket(server, port);
        OutputStream os = sckt.getOutputStream();
        //PrintWriter sckt_out = new PrintWriter(os, true);

        Integer cnt = 0;

        st = LocalDateTime.now();

        Double ns_delay = 1000000000.0 / (double) rate;

        long ns = ns_delay.longValue();
        if (ns < 0) {
            ns = 0;
        }

        while (cnt < numEvents) {
            cnt += 1;
            LocalDateTime ct = LocalDateTime.now();
            String dtg = ct.toString();
            Double lat = 180 * rnd.nextDouble() - 90.0;
            Double lon = 360 * rnd.nextDouble() - 180.0;
            String line = "RandomPoint," + cnt.toString() + "," + dtg + ",\"" + lon.toString() + ","
                    + lat.toString() + "\"," + cnt.toString() + "\n";

            final long stime = System.nanoTime();

            long etime = 0;
            do {
                etime = System.nanoTime();
            } while (stime + ns >= etime);

            if (cnt % 1000 == 0) {
                //System.out.println(cnt);
            }

            //sckt_out.write(line);
            os.write(line.getBytes());
            os.flush();

        }

        if (st != null) {
            LocalDateTime et = LocalDateTime.now();

            Duration delta = Duration.between(st, et);

            Double elapsed_seconds = (double) delta.getSeconds() + delta.getNano() / 1000000000.0;

            send_rate = (double) numEvents / elapsed_seconds;
        }

        //sckt_out.close();
        sckt.close();
        os = null;
        //sckt_out = null;

    } catch (Exception e) {
        System.err.println(e.getMessage());
        send_rate = -1.0;
    } finally {
        try {
            br.close();
        } catch (Exception e) {
            //
        }

        this.send_rate = send_rate;

    }

}

From source file:com.amazonaws.util.TimingInfo.java

/**
 * Captures the current wall clock time (since epoch in millisecond)
 * and the current time (in nanosecond) used for timing measurement.
 * For more info, see:/*from   w ww.ja v  a2 s.c  om*/
 * https://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks
 */
public static TimingInfo startTimingFullSupport() {
    return new TimingInfoFullSupport(Long.valueOf(System.currentTimeMillis()), System.nanoTime(), null);
}