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:CodeTimer.java

/**
 * Call to start a profiling period, or to start an interval in an open
 * period//from  ww  w .j a  v a 2  s . c om
 * 
 * @param name
 *            A helpful name for this interval. Makes it easy to find what
 *            bit of code you're measuring
 */
public void tick(String name) {
    if (enabled) {
        long clickTime = System.nanoTime();

        if (!periodStarted) {
            periodStarted = true;
            periodStartTime = clickTime;

            intervalNames[0] = name;
        } else {
            long duration = clickTime - lastClickTime;
            intervalDurationSums[intervalIndex] += duration;

            intervalIndex++;

            if (intervalIndex >= intervalNames.length) {
                intervalNames = ArrayUtil.grow(intervalNames);
                intervalDurationSums = ArrayUtil.grow(intervalDurationSums);
            }

            intervalNames[intervalIndex] = name;
        }

        lastClickTime = clickTime;
    }
}

From source file:com.garethahealy.karaf.commands.ensemble.healthy.EnsembleHealthyAction.java

protected Boolean waitForEnsembleHealthy() throws InterruptedException {
    Boolean hasTimedOut = false;/*from  ww w .j ava2 s . co  m*/

    Long currentTime = System.nanoTime();
    Long waitTimeout = currentTime + TimeUnit.MILLISECONDS.toNanos(wait);

    while (!hasTimedOut) {
        List<String> containersInEnsemble = clusterService.getEnsembleContainers();

        //Sort them to be alphabetical
        Collections.sort(containersInEnsemble);

        Boolean isEqualList = ListUtils.isEqualList(containers, containersInEnsemble);
        if (isEqualList) {
            log.trace("MATCH: Expected: {}, Result: {}", StringUtils.join(containers, ','),
                    StringUtils.join(containersInEnsemble, ','));

            System.out.println(
                    String.format(FORMAT, "Ensemble List: ", StringUtils.join(containersInEnsemble, ',')));
            System.out.println("Ensemble Healthy: success");
            break;

        } else {
            log.trace("NON-MATCH: Expected: {}, Result: {}. Waiting...", StringUtils.join(containers, ','),
                    StringUtils.join(containersInEnsemble, ','));
        }

        currentTime = System.nanoTime();
        if (currentTime > waitTimeout) {
            log.trace("Ensemble of {} took too long. Current time {}ns is greater than wait {}ns",
                    StringUtils.join(containers, ','), currentTime, waitTimeout);

            hasTimedOut = true;
            break;
        }

        //Probably not the best way, but does its job
        TimeUnit.MILLISECONDS.sleep(tick);
    }

    return hasTimedOut;
}

From source file:org.openvpms.component.business.service.lookup.LookupTestCase.java

/**
 * Test that we can create an object through this service.
 *//*from w ww  . jav  a2  s . co m*/
@Test
public void testLookupObjectCreation() {
    for (int index = 0; index < 5; index++) {
        Lookup lookup = (Lookup) create("lookup.country");

        // make sure the code is unique
        lookup.setCode("AU-" + System.nanoTime());
        lookup.setName("Australia");

        // insert the lookup object
        save(lookup);
    }
}

From source file:com.kircherelectronics.accelerationexplorer.filter.MedianFilterSmoothing.java

/**
 * Filter the data./*ww w  . ja  v a2 s .com*/
 * 
 * @param iterator
 *            contains input the data.
 * @return the filtered output data.
 */
public float[] addSamples(float[] data) {
    // Initialize the start time.
    if (startTime == 0) {
        startTime = System.nanoTime();
    }

    timestamp = System.nanoTime();

    // Find the sample period (between updates) and convert from
    // nanoseconds to seconds. Note that the sensor delivery rates can
    // individually vary by a relatively large time frame, so we use an
    // averaging technique with the number of sensor updates to
    // determine the delivery rate.
    hz = (count++ / ((timestamp - startTime) / 1000000000.0f));

    filterWindow = (int) (hz * timeConstant);

    for (int i = 0; i < data.length; i++) {
        // Initialize the data structures for the data set.
        if (!dataInit) {
            dataLists.add(new LinkedList<Number>());
        }

        dataLists.get(i).addLast(data[i]);

        if (dataLists.get(i).size() > filterWindow) {
            dataLists.get(i).removeFirst();
        }
    }

    dataInit = true;

    float[] medians = new float[dataLists.size()];

    for (int i = 0; i < dataLists.size(); i++) {
        medians[i] = (float) getMedian(dataLists.get(i));
    }

    return medians;
}

From source file:de.hofuniversity.iisys.neo4j.websock.query.encoding.logging.LoggingTSafeJsonQueryHandler.java

@Override
public String encode(final WebsockQuery query) throws EncodeException {
    String result = null;//  w  w  w.  j a  v a 2  s. c  o  m

    try {
        long time = System.nanoTime();
        final JSONObject obj = JsonConverter.toJson(query);
        result = obj.toString();
        time = System.nanoTime() - time;

        if (fDebug) {
            fTotalBytesOut += result.getBytes().length;
            fLogger.log(Level.FINEST, "encoded JSON message: " + result.getBytes().length + " bytes\n"
                    + "total bytes sent: " + fTotalBytesOut);
        }

        //store query type
        final String type = query.getPayload().toString();
        synchronized (QUERY_TYPES) {
            QUERY_TYPES.put(query.getId(), type);
        }

        if (LOGGING_ENABLED) {
            //store size of query
            List<Integer> sizes = null;
            synchronized (LOGGED_OUT_SIZES) {
                sizes = LOGGED_OUT_SIZES.get(type);

                if (sizes == null) {
                    sizes = new LinkedList<Integer>();
                    LOGGED_OUT_SIZES.put(type, sizes);
                }
            }

            synchronized (sizes) {
                sizes.add(result.getBytes().length);
            }

            //store time taken
            List<Long> times = null;
            synchronized (LOGGED_OUT_TIMES) {
                times = LOGGED_OUT_TIMES.get(type);

                if (times == null) {
                    times = new LinkedList<Long>();
                    LOGGED_OUT_TIMES.put(type, times);
                }
            }

            synchronized (times) {
                times.add(time);
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new EncodeException(query, "failed to encode JSON", e);
    }

    return result;
}

From source file:ffx.algorithms.AlgorithmUtils.java

/**
 * Logs time since this interface was created and the last time this method
 * was called. May be more elegant to replace this by using protected
 * variables and simply inheriting the time() function.
 *
 * @return Time since last call (double).
 *///from   www .  j  av  a2 s  . co  m
@Override
public double time() {
    long currTime = System.nanoTime();
    logger.info(String.format(" Time since interface established: %f", (currTime - initTime) * 1.0E-9));
    double elapsed = (currTime - interTime) * 1.0E-9;
    interTime = currTime;
    logger.info(String.format(" Time since last timer call: %f", elapsed));
    return elapsed;
}

From source file:net.sourceforge.subsonic.dao.AbstractDao.java

protected <T> List<T> query(String sql, RowMapper rowMapper, Object... args) {
    long t = System.nanoTime();
    List<T> result = getJdbcTemplate().query(sql, args, rowMapper);
    log(sql, t);// w w w .  ja  v a  2 s  .  co  m
    return result;
}

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

private void f_jackson() throws Exception {
    long startNano = System.nanoTime();
    for (int i = 0; i < COUNT; ++i) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.readTree(text);/* w w w . java  2s. c o  m*/
        // JsonNode head = node.get(0);
        // JsonNode body = node.get(1);
    }
    long nano = System.nanoTime() - startNano;
    System.out.println("jackson \t: " + NumberFormat.getInstance().format(nano));
}

From source file:com.netflix.genie.web.jobs.workflow.impl.InitialSetupTask.java

/**
 * {@inheritDoc}//  w  w w . ja  va 2s.co m
 */
@Override
public void executeTask(@NotNull final Map<String, Object> context) throws GenieException, IOException {
    final long start = System.nanoTime();
    final Set<Tag> tags = Sets.newHashSet();
    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 Initial Setup Task for job {}", jobId);

        this.createJobDirStructure(jobWorkingDirectory);

        // set the env variables in the launcher script
        this.createJobDirEnvironmentVariables(writer, jobWorkingDirectory);
        this.createApplicationEnvironmentVariables(writer);

        // create environment variables for the command
        final Command command = jobExecEnv.getCommand();
        this.createCommandEnvironmentVariables(writer, command);

        // create environment variables for the cluster
        final Cluster cluster = jobExecEnv.getCluster();
        this.createClusterEnvironmentVariables(writer, cluster);

        // create environment variable for the job itself
        this.createJobEnvironmentVariables(writer, jobId, jobExecEnv.getJobRequest().getName(),
                jobExecEnv.getMemory(), jobExecEnv.getJobRequest().getTags(),
                jobExecEnv.getJobRequest().getGrouping().orElse(""),
                jobExecEnv.getJobRequest().getGroupingInstance().orElse(""));

        // create environment variables for the job request
        this.createJobRequestEnvironmentVariables(writer, jobExecEnv.getJobRequest());

        //Export the Genie Version
        writer.write(GENIE_VERSION_EXPORT);
        writer.write(LINE_SEPARATOR);
        writer.write(LINE_SEPARATOR);

        log.info("Finished Initial Setup Task for job {}", jobId);
        MetricsUtils.addSuccessTags(tags);
    } catch (final Throwable t) {
        MetricsUtils.addFailureTagsWithException(tags, t);
        throw t;
    } finally {
        this.getRegistry().timer(SETUP_TASK_TIMER_NAME, tags).record(System.nanoTime() - start,
                TimeUnit.NANOSECONDS);
    }
}

From source file:no.ntnu.okse.core.topic.Topic.java

/**
 * Private method that generates an MD5 topic ID
 *
 * @return A string containing the generated topicID
 *///from w w  w. ja v a2  s  . com
private String generateTopicID() {
    try {
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.update(Long.toString(System.nanoTime()).getBytes());
        byte[] hash = m.digest();
        String topicID = new String(Hex.encode(hash));

        return topicID;
    } catch (NoSuchAlgorithmException e) {
        log.error("Could not generate a topic ID (MD5 algorithm not found)");
    }

    return null;
}