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:org.jhk.pulsing.pulse.TrendingPulseSubTest.java

private static Map<String, Integer> createTempMap() {
    Map<String, Integer> temp = new HashMap<>();

    //Structure is <id>0x07<value>0x13<timestamp> -> count; i.e. {"10020x07Mocked 10020x13<timestamp>" -> 1}
    //technically multiple Map -> String exists in the DB, but for now use single one for test
    String joinedKey = String.join("", "500", CommonConstants.TIME_INTERVAL_ID_VALUE_DELIM, "Mocked 500",
            CommonConstants.TIME_INTERVAL_PERSIST_TIMESTAMP_DELIM, System.nanoTime() + "");

    temp.put(joinedKey, 3);//from  w w  w. jav a  2  s .  c  o m

    joinedKey = String.join("", "500", CommonConstants.TIME_INTERVAL_ID_VALUE_DELIM, "Mocked 500",
            CommonConstants.TIME_INTERVAL_PERSIST_TIMESTAMP_DELIM, System.nanoTime() + "");

    temp.put(joinedKey, 1);

    joinedKey = String.join("", "500", CommonConstants.TIME_INTERVAL_ID_VALUE_DELIM, "Mocked 500",
            CommonConstants.TIME_INTERVAL_PERSIST_TIMESTAMP_DELIM, System.nanoTime() + "");

    temp.put(joinedKey, 1);

    joinedKey = String.join("", "200", CommonConstants.TIME_INTERVAL_ID_VALUE_DELIM, "Mocked 200",
            CommonConstants.TIME_INTERVAL_PERSIST_TIMESTAMP_DELIM, System.nanoTime() + "");

    temp.put(joinedKey, 1);

    joinedKey = String.join("", "200", CommonConstants.TIME_INTERVAL_ID_VALUE_DELIM, "Mocked 200",
            CommonConstants.TIME_INTERVAL_PERSIST_TIMESTAMP_DELIM, System.nanoTime() + "");

    temp.put(joinedKey, 1);

    joinedKey = String.join("", "100", CommonConstants.TIME_INTERVAL_ID_VALUE_DELIM, "Mocked 100",
            CommonConstants.TIME_INTERVAL_PERSIST_TIMESTAMP_DELIM, System.nanoTime() + "");

    temp.put(joinedKey, 1);
    return temp;
}

From source file:com.github.seleniumpm.Selenium10.java

public Selenium waitForPresent(Object locator, long waitTime) throws NotFoundException {
    long currentTime = System.nanoTime();
    long endTime = currentTime + TimeUnit.MILLISECONDS.toNanos(elementWaitTime);

    while (currentTime <= endTime) {
        if (isPresent(locator))
            return this;
        try {//from  w ww.j a va 2  s. com
            Thread.sleep(sleepTimeInMilis);
        } catch (InterruptedException ie) {
            throw new NotFoundException("An InterruptedException occured!");
        }
        currentTime = System.nanoTime();
    }
    throw new NotFoundException(locator + "was not found in " + elementWaitTime + "ms!");
}

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

/**
 * {@inheritDoc}/*  w  w  w  .j  av a2  s.  c  o 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 Command command = jobExecEnv.getCommand();
        tags.add(Tag.of(MetricsConstants.TagKeys.COMMAND_NAME, command.getMetadata().getName()));
        tags.add(Tag.of(MetricsConstants.TagKeys.COMMAND_ID, command.getId()));
        final String jobWorkingDirectory = jobExecEnv.getJobWorkingDir().getCanonicalPath();
        final String genieDir = jobWorkingDirectory + JobConstants.FILE_PATH_DELIMITER
                + JobConstants.GENIE_PATH_VAR;
        final Writer writer = (Writer) context.get(JobConstants.WRITER_KEY);

        log.info("Starting Command Task for job {}", jobExecEnv.getJobRequest().getId().orElse(NO_ID_FOUND));

        final String commandId = command.getId();

        // Create the directory for this command under command dir in the cwd
        createEntityInstanceDirectory(genieDir, commandId, AdminResources.COMMAND);

        // Create the config directory for this id
        createEntityInstanceConfigDirectory(genieDir, commandId, AdminResources.COMMAND);

        // Create the dependencies directory for this id
        createEntityInstanceDependenciesDirectory(genieDir, commandId, AdminResources.COMMAND);

        // Get the setup file if specified and add it as source command in launcher script
        final Optional<String> setupFile = command.getResources().getSetupFile();
        if (setupFile.isPresent()) {
            final String commandSetupFile = setupFile.get();
            if (StringUtils.isNotBlank(commandSetupFile)) {
                final String localPath = super.buildLocalFilePath(jobWorkingDirectory, commandId,
                        commandSetupFile, FileType.SETUP, AdminResources.COMMAND);

                fts.getFile(commandSetupFile, localPath);

                super.generateSetupFileSourceSnippet(commandId, "Command:", localPath, writer,
                        jobWorkingDirectory);
            }
        }

        // Iterate over and get all configuration files
        for (final String configFile : command.getResources().getConfigs()) {
            final String localPath = super.buildLocalFilePath(jobWorkingDirectory, commandId, configFile,
                    FileType.CONFIG, AdminResources.COMMAND);
            fts.getFile(configFile, localPath);
        }

        // Iterate over and get all dependencies
        for (final String dependencyFile : command.getResources().getDependencies()) {
            final String localPath = super.buildLocalFilePath(jobWorkingDirectory, commandId, dependencyFile,
                    FileType.DEPENDENCIES, AdminResources.COMMAND);
            fts.getFile(dependencyFile, localPath);
        }
        log.info("Finished Command Task for job {}", jobExecEnv.getJobRequest().getId().orElse(NO_ID_FOUND));
        MetricsUtils.addSuccessTags(tags);
    } catch (Throwable t) {
        MetricsUtils.addFailureTagsWithException(tags, t);
        throw t;
    } finally {
        this.getRegistry().timer(COMMAND_TASK_TIMER_NAME, tags).record(System.nanoTime() - start,
                TimeUnit.NANOSECONDS);
    }
}

From source file:com.mitchellbosecke.pebble.spring.PebbleView.java

@Override
protected void renderMergedTemplateModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    response.setCharacterEncoding(this.characterEncoding);

    long startNanos = System.nanoTime();

    PebbleTemplate template = this.engine.getTemplate(this.templateName);

    // Add beans context
    model.put(BEANS_VARIABLE_NAME, new Beans(this.getApplicationContext()));

    // Add request & response
    model.put(REQUEST_VARIABLE_NAME, request);
    model.put(RESPONSE_VARIABLE_NAME, response);

    // Add session
    model.put(SESSION_VARIABLE_NAME, request.getSession(false));

    // Locale/*w w w .j  a va  2s. c  o  m*/
    Locale locale = RequestContextUtils.getLocale(request);

    final Writer writer = response.getWriter();
    try {
        template.evaluate(writer, model, locale);
    } finally {
        writer.flush();
    }

    if (TIMER_LOGGER.isDebugEnabled()) {
        long endNanos = System.nanoTime();

        BigDecimal elapsed = BigDecimal.valueOf(endNanos - startNanos);
        BigDecimal elapsedMs = elapsed.divide(BigDecimal.valueOf(NANOS_IN_SECOND), RoundingMode.HALF_UP);
        TIMER_LOGGER.debug("Pebble template \"{}\" with locale {} processed in {} nanoseconds (approx. {}ms)",
                new Object[] { this.templateName, locale, elapsed, elapsedMs });
    }
}

From source file:edu.stevens.cpe.reservior.Reservoir.java

public Reservoir(int neuronCount, NetworkTopology topology, Class<T> clazz) throws ReserviorException {
    startTime = System.nanoTime();
    this.neuronCount = neuronCount;
    this.topology = topology;
    this.neuronClass = clazz;

    try {//from w  w  w  . j a  v  a2  s. c  om

        createNeurons();
        //TODO move me to network
        System.setProperty("org.bushe.swing.event.eventBusClass",
                "org.bushe.swing.event.DiscreteTimeThreadSafeEventService");
        EventServiceLocator.setEventService("DiscreteTimeThreadSafeEventService",
                new DiscreteTimeThreadSafeEventService());
        initConnections();

    } catch (IllegalArgumentException e) {
        throw new ReserviorException(e);
    } catch (SecurityException e) {
        throw new ReserviorException(e);
    } catch (InstantiationException e) {
        throw new ReserviorException(e);
    } catch (IllegalAccessException e) {
        throw new ReserviorException(e);
    } catch (InvocationTargetException e) {
        throw new ReserviorException(e);
    } catch (NoSuchMethodException e) {
        throw new ReserviorException(e);
    } catch (EventServiceExistsException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:software.uncharted.rest.ImageSearchResource.java

@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ImageSearchResult searchByUrl(@RequestBody final JsonNode body) throws IOException {
    long start = System.nanoTime();
    String url = JSONUtil.getString(body, "url");
    Set<Image> images = service.search(url);
    long duration = (System.nanoTime() - start) / 1000000L;
    return new ImageSearchResult().setImages(images).setDuration(duration);
}

From source file:com.espertech.esper.regression.client.TestThreadedConfigTimer.java

public void testOp() throws Exception {
    Configuration config = SupportConfigFactory.getConfiguration();
    config.getEngineDefaults().getThreading().setInternalTimerEnabled(false);
    config.getEngineDefaults().getExpression().setUdfCache(false);
    config.getEngineDefaults().getThreading().setThreadPoolTimerExec(true);
    config.getEngineDefaults().getThreading().setThreadPoolTimerExecNumThreads(5);
    config.addEventType("MyMap", new HashMap<String, Object>());
    config.addImport(SupportStaticMethodLib.class.getName());

    EPServiceProvider epService = EPServiceProviderManager.getDefaultProvider(config);
    epService.initialize();/*from   w  w w  . ja  v  a 2s.  co m*/
    sendTimer(0, epService);

    log.debug("Creating statements");
    int countStatements = 100;
    SupportListenerTimerHRes listener = new SupportListenerTimerHRes();
    for (int i = 0; i < countStatements; i++) {
        EPStatement stmt = epService.getEPAdministrator().createEPL(
                "select SupportStaticMethodLib.sleep(10) from pattern[every MyMap -> timer:interval(1)]");
        stmt.addListener(listener);
    }

    log.info("Sending trigger event");
    epService.getEPRuntime().sendEvent(new HashMap<String, Object>(), "MyMap");

    long start = System.nanoTime();
    sendTimer(1000, epService);
    long end = System.nanoTime();
    long delta = (end - start) / 1000000;
    assertTrue("Delta is " + delta, delta < 100);

    // wait for delivery
    while (true) {
        int countDelivered = listener.getNewEvents().size();
        if (countDelivered == countStatements) {
            break;
        }

        log.info("Delivered " + countDelivered + ", waiting for more");
        Thread.sleep(200);
    }

    assertEquals(100, listener.getNewEvents().size());
    // analyze result
    //List<Pair<Long, EventBean[]>> events = listener.getNewEvents();
    //OccuranceResult result = OccuranceAnalyzer.analyze(events, new long[] {100 * 1000 * 1000L, 10*1000 * 1000L});
    //log.info(result);
}

From source file:com.zht.common.rabc.service.impl.RbacUserServiceImpl.java

public void genUSer(String userName, String password) {
    RbacUser user = new RbacUser();
    String salt = System.nanoTime() + UUIDUtil.base58Uuid() + new Md5Hash(userName).toString();
    ;///*from w  ww .  j  a  v  a 2 s .c  o  m*/
    // String password_cipherText2= new Md5Hash(password,salt,2).toString(); 
    user.setSalt(salt);
}

From source file:TimeResolution.java

/**
 * Measures how much time has elapsed according to both currentTimeMillis()
 * and nanoTime() at each interval. Note that the time reported for 
 * sleep() may not be accurate since the internal sleep timer may not
 * have the appropriate resolution to sleep for the requested time.
 * The main utility of this function is to compare the two timing
 * functions, although it is also interesting to see how the measured
 * time varies from the sleep() time./*from w ww  . ja va  2  s .  c om*/
 */
private void measureTimeFunctions(int increment, int max) {
    long startTime = System.currentTimeMillis();
    long startNanos = System.nanoTime();
    long elapsedTimeActual = 0;
    long elapsedTimeMeasured = 0;
    long elapsedNanosMeasured = 0;
    System.out.printf("sleep   currentTimeMillis   nanoTime\n");
    while (elapsedTimeActual < max) {
        try {
            Thread.sleep(increment);
        } catch (Exception e) {
        }
        long currentTime = System.currentTimeMillis();
        long currentNanos = System.nanoTime();
        elapsedTimeActual += increment;
        elapsedTimeMeasured = currentTime - startTime;
        elapsedNanosMeasured = (currentNanos - startNanos) / 1000000;
        System.out.printf(" %3d           %4d          %4d\n", elapsedTimeActual, elapsedTimeMeasured,
                elapsedNanosMeasured);
    }
}

From source file:ca.brood.softlogger.dataoutput.CSVOutputModule.java

public CSVOutputModule() {
    super();//from   w w w .j av  a  2 s. c  om
    log = Logger.getLogger(CSVOutputModule.class);
    writer = null;
    logSchedulable = new PrettyPeriodicSchedulable();
    fileCreateSchedulable = new PrettyPeriodicSchedulable();
    firstLineOutputted = false;
    firstFileCreated = false;
    writeGuids = true;
    completedFileDirectory = "";
    csvSubdirectory = ".";
    nanoTimeOffset = System.nanoTime();
}