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:fr.xebia.monitoring.demo.payment.CreditCardServiceAuditingImpl.java

@Override
public PaymentTransaction purchase(MonetaryAmount total, Order order, String requestId) {
    StringBuilder auditMessage = new StringBuilder("creditcardservice.purchase(" + requestId + ", "
            + order.getAccount().getEmail() + ", " + total + ") by ");
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
        auditMessage.append("anonymous");
    } else {//from w  w w .java 2 s  . c o m
        auditMessage.append(authentication.getName());
        if (authentication.getDetails() instanceof WebAuthenticationDetails) {
            WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
            auditMessage.append(" coming from " + details.getRemoteAddress());
        }
    }

    long nanosBefore = System.nanoTime();
    try {
        PaymentTransaction paymentTransaction = creditCardService.purchase(total, order, requestId);

        auditMessage.append(" SUCCESS ").append(paymentTransaction.getTransactionId());
        auditMessage.append(" in ")
                .append(TimeUnit.MILLISECONDS.convert(System.nanoTime() - nanosBefore, TimeUnit.NANOSECONDS))
                .append(" ms");
        auditLogger.info(auditMessage.toString());
        return paymentTransaction;
    } catch (RuntimeException e) {
        auditMessage.append(" FAILURE ").append(Joiner.on(", ").join(Throwables.getCausalChain(e)));
        auditMessage.append(" in ")
                .append(TimeUnit.MILLISECONDS.convert(System.nanoTime() - nanosBefore, TimeUnit.NANOSECONDS))
                .append(" ms");
        auditLogger.warn(auditMessage.toString());
        throw e;
    }

}

From source file:hsa.awp.scire.procedureLogic.DrawProcedureLogic.java

/**
 * Default constructor./*from ww w  .j a  va 2s  .  co m*/
 */
public DrawProcedureLogic() {

    super(DrawProcedure.class);
    this.rand = new Random(System.nanoTime());
}

From source file:net.arp7.HdfsPerfTest.WriteFile.java

private static void writeFiles(final Configuration conf, final FileIoStats stats)
        throws InterruptedException, IOException {
    final FileSystem fs = FileSystem.get(conf);
    final AtomicLong filesLeft = new AtomicLong(params.getNumFiles());
    final long runId = abs(rand.nextLong());
    final byte[] data = new byte[params.getIoSize()];
    Arrays.fill(data, (byte) 65);

    // Start the writers.
    final ExecutorService executor = Executors.newFixedThreadPool((int) params.getNumThreads());
    final CompletionService<Object> ecs = new ExecutorCompletionService<>(executor);
    LOG.info("NumFiles=" + params.getNumFiles() + ", FileSize="
            + FileUtils.byteCountToDisplaySize(params.getFileSize()) + ", IoSize="
            + FileUtils.byteCountToDisplaySize(params.getIoSize()) + ", BlockSize="
            + FileUtils.byteCountToDisplaySize(params.getBlockSize()) + ", ReplicationFactor="
            + params.getReplication() + ", isThrottled=" + (params.maxWriteBps() > 0));
    LOG.info("Starting " + params.getNumThreads() + " writer thread" + (params.getNumThreads() > 1 ? "s" : "")
            + ".");
    final long startTime = System.nanoTime();
    for (long t = 0; t < params.getNumThreads(); ++t) {
        final long threadIndex = t;
        Callable<Object> c = new Callable<Object>() {
            @Override//  w  w  w.  j  a  v a 2s .  co m
            public Object call() throws Exception {
                long fileIndex = 0;
                while (filesLeft.addAndGet(-1) >= 0) {
                    final String fileName = "WriteFile-" + runId + "-" + (threadIndex + 1) + "-"
                            + (++fileIndex);
                    writeOneFile(new Path(params.getOutputDir(), fileName), fs, data, stats);
                }
                return null;
            }
        };
        ecs.submit(c);
    }

    // And wait for all writers to complete.
    for (long t = 0; t < params.getNumThreads(); ++t) {
        ecs.take();
    }
    final long endTime = System.nanoTime();
    stats.setElapsedTime(endTime - startTime);
    executor.shutdown();
}

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

@RequestMapping(value = "/histogram/{histogram}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ImageSearchResult searchByHash(@PathVariable("histogram") final String histogram) {
    long start = System.nanoTime();
    Set<Image> images = service.searchByHistogram(histogram);
    long duration = (System.nanoTime() - start) / 1000000L;
    return new ImageSearchResult().setImages(images).setDuration(duration);

}

From source file:com.kellerkindt.scs.utilities.Utilities.java

public static String getRandomSha1(String s) {
    String sha1 = new Random().nextDouble() + s + System.nanoTime();

    try {/*  ww  w .  j  a  va  2s  . c  o m*/
        sha1 = sha1(sha1);
    } catch (IOException ioe) {
    }

    return sha1;
}

From source file:com.scaleoutsoftware.soss.hserver.DatasetRecordReader.java

@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
    long time;/*from  www.  ja  v a 2  s. c  o  m*/
    initialize = System.nanoTime() - initialize;
    time = System.nanoTime();
    boolean hasNext = currentRecordReader.nextKeyValue();
    time = System.nanoTime() - time;

    if (first == 0)
        first = time;
    maxTime = Math.max(maxTime, time);
    minTime = Math.min(minTime, time);
    totalTime += time;

    if (hasNext) {
        numberOfRecors++;
    }

    if (!hasNext && numberOfRecors > 1) {
        LOG.debug("Record reader done. #rec = " + numberOfRecors + "; Total=" + totalTime + " ns; Per_rec = "
                + (totalTime / numberOfRecors) + " ns. First = " + first + "; Max = " + maxTime + "; Min"
                + minTime + " Initial = " + initialize);
    }

    return hasNext;
}

From source file:ml.shifu.guagua.hadoop.ZooKeeperWorkerInterceptor.java

@Override
public void preApplication(WorkerContext<MASTER_RESULT, WORKER_RESULT> context) {
    String zkServers = context.getProps().getProperty(GuaguaConstants.GUAGUA_ZK_SERVERS);
    if (zkServers == null || zkServers.length() == 0 || !ZooKeeperUtils.checkServers(zkServers)) {
        this.sleepTime = NumberFormatUtils.getLong(
                context.getProps().getProperty(GuaguaConstants.GUAGUA_COORDINATOR_SLEEP_UNIT), WAIT_SLOT_MILLS);
        this.isFixedTime = Boolean.TRUE.toString().equalsIgnoreCase(
                context.getProps().getProperty(GuaguaConstants.GUAGUA_COORDINATOR_FIXED_SLEEP_ENABLE,
                        GuaguaConstants.GUAGUA_COORDINATOR_FIXED_SLEEP));

        String hdfsZookeeperServerFolder = getZookeeperServerFolder(context);
        long start = System.nanoTime();
        while (true) {
            if (TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start) > 10 * 60 * 1000L) {
                throw new GuaguaRuntimeException("Cannot get zookeeper server address in 10 minutes.");
            }//from   w  ww.jav  a  2 s.  com
            BufferedReader br = null;
            try {
                final FileSystem fileSystem = FileSystem.get(new Configuration());
                final Path zookeeperServerPath = fileSystem.makeQualified(new Path(hdfsZookeeperServerFolder,
                        GuaguaConstants.GUAGUA_CLUSTER_ZOOKEEPER_SERVER_FILE));
                LOG.info("Embeded zookeeper server address is {}", zookeeperServerPath);

                new RetryCoordinatorCommand(this.isFixedTime, this.sleepTime) {
                    @Override
                    public boolean retryExecution() throws Exception, InterruptedException {
                        return fileSystem.exists(zookeeperServerPath);
                    }
                }.execute();

                FSDataInputStream fis = fileSystem.open(zookeeperServerPath);
                br = new BufferedReader(new InputStreamReader(fis));
                String zookeeperServer = br.readLine();
                if (zookeeperServer == null || zookeeperServer.length() == 0) {
                    LOG.warn("Cannot get zookeeper server in {} ", zookeeperServerPath.toString());
                    // retry
                    continue;
                }
                // set server info to context for next intercepters.
                LOG.info("Embeded zookeeper instance is {}", zookeeperServer);
                context.getProps().setProperty(GuaguaConstants.GUAGUA_ZK_SERVERS, zookeeperServer);
                break;
            } catch (Throwable t) {
                LOG.warn(String.format("Error in get zookeeper address message: %s", t.getMessage()));
                continue;
            } finally {
                IOUtils.closeQuietly(br);
            }
        }
    }
}

From source file:com.autobizlogic.abl.rule.FormulaRule.java

/**
 * Execute this formula method in a LogicObject
 *//*from  ww  w. j  av a2s  .  c o m*/
public boolean execute(Object aLogicObject, LogicRunner aLogicRunner) {

    long startTime = System.nanoTime();
    boolean rtnDidExecute = false;
    String theLogicMethodName = getLogicMethodName();
    Object result = null;
    if (pruning && isFormulaPrunable(aLogicRunner)) {
        if (log.isDebugEnabled())
            log.debug("Formula pruned " + getBeanAttributeName(), aLogicRunner);
        return false; // Note that we do not fire any event since the formula was not executed
    }

    PersistentBean currentDomainObject = aLogicRunner.getCurrentDomainObject();

    // Is the formula expressed in the annotation? If so, we evaluate it, and we call
    // the method as a courtesy but ignore its return value.
    if (expression != null && expression.trim().length() > 0) {
        result = evaluateExpression(currentDomainObject, aLogicRunner.getLogicContext());

        MetaAttribute metaAttribute = currentDomainObject.getMetaEntity()
                .getMetaAttribute(getBeanAttributeName());
        Object convertedResult = ObjectUtil.convertToDataType(result, metaAttribute.getType());

        Object oldValue = currentDomainObject.get(getBeanAttributeName());

        // If the formula has the same value as the stored value, there is nothing to do, and the formula should not
        // be considered to have really fired.
        if (!((oldValue == null && result == null)
                || (oldValue != null && result != null && oldValue.equals(result)))) {
            currentDomainObject.put(getBeanAttributeName(), convertedResult);
            rtnDidExecute = true;

            if ("true".equals(
                    LogicConfiguration.getInstance().getProperty(PropertyName.INVOKE_FORMULA_METHODS))) {
                try { // Then call the method for debugging purposes, but ignore its return value
                    MethodInvocationUtil.invokeMethodOnObject(aLogicObject, theLogicMethodName);
                } catch (Exception ex) {
                    if (log.isWarnEnabled())
                        log.warn("Formula method " + this.getLogicGroup().getLogicClassName() + "."
                                + this.getLogicMethodName() + " threw an exception. This is not fatal because "
                                + "the formula has an expression in its declaration, and therefore the method itself "
                                + "is called purely as a courtesy, but this should be examined. The exception was: "
                                + ex);
                }
            }

            firePostEvent(aLogicObject, aLogicRunner, oldValue, System.nanoTime() - startTime);
        }

        if (rtnDidExecute && log.isDebugEnabled())
            log.debug("Formula changes attribute " + getBeanAttributeName() + " -> " + convertedResult + " on",
                    aLogicRunner);

        return rtnDidExecute;
    }

    // If the formula is not expressed in the annotation, it must be in the code

    if (!"true".equals(LogicConfiguration.getInstance().getProperty(PropertyName.INVOKE_FORMULA_METHODS))) {
        throw new RuntimeException(toString()
                + " does not have an annotation-based definition, but the ABL configuration "
                + "specifies that formula methods should not be invoked. If you wish to enable formula methods, you should change "
                + "your ABLConfig.properties file to indicate that with: invokeFormulaMethods=true");
    }

    try {
        result = MethodInvocationUtil.invokeMethodOnObject(aLogicObject, theLogicMethodName);
        if (result == null && getLogicGroup().isGroovy()) {
            if (sysLog.isDebugEnabled())
                sysLog.debug("Groovy formula returns null, value unchanged " + getBeanAttributeName(),
                        aLogicRunner);

        } else {
            if (result != null && result.equals(LogicContext.nullValue) && getLogicGroup().isGroovy()) {
                result = null;
            }
            currentDomainObject = aLogicRunner.getCurrentDomainObject();
            Object oldValue = currentDomainObject.get(getBeanAttributeName());

            // If the formula has the same value as the stored value, there is nothing to do, and the formula should not
            // be considered to have really fired.
            if (!((oldValue == null && result == null)
                    || (oldValue != null && result != null && oldValue.equals(result)))) {
                currentDomainObject.put(getBeanAttributeName(), result);
                rtnDidExecute = true;
                firePostEvent(aLogicObject, aLogicRunner, oldValue, System.nanoTime() - startTime);
            }

            if (rtnDidExecute && log.isDebugEnabled())
                log.debug("Formula changes attribute " + getBeanAttributeName() + " -> " + result + " on",
                        aLogicRunner);
        }
    } catch (Exception e) {
        throw new LogicException(
                "Failure setting formula for : " + getBeanAttributeName() + " on: " + currentDomainObject, e);
    }

    return rtnDidExecute;
}

From source file:net.rhapso.koa.tree.IOTest.java

private void doRun(int howMany, int samplingRate, Tree tree, Cache cache) {
    long insertionElapsed = 0;
    long retrievalElapsed = 0;

    tree.put(new Key(new byte[1]), new Value(0));
    System.out.println("keyCount, writeThroughput, readThroughput, cacheHitRatio, cacheFillRatio");
    for (int i = 0; i < howMany; i++) {
        byte[] bytes = makeRandomBytes(100);
        Key key = new Key(bytes);
        long insertionThen = System.nanoTime();
        tree.put(key, new Value(0));
        insertionElapsed += System.nanoTime() - insertionThen;

        long retrievalThen = System.nanoTime();
        boolean containsKey = tree.contains(key);
        retrievalElapsed += System.nanoTime() - retrievalThen;
        if (!containsKey) {
            fail();//from  w  w w . ja  v  a  2 s . c o m
        }

        if (i != 0 && i % samplingRate == 0) {
            CacheStatistics cacheStatistics = cache.resetStatistics();
            long avgInsertionTime = insertionElapsed / samplingRate;
            long avgRetrievalTime = retrievalElapsed / samplingRate;

            double writeThroughput = 1000000000d / (double) avgInsertionTime;
            double readThroughput = 1000000000d / (double) avgRetrievalTime;

            System.out.println(i + "," + writeThroughput + "," + readThroughput + ","
                    + cacheStatistics.hitRatio() + "," + cacheStatistics.fillRatio());
            insertionElapsed = 0;
            retrievalElapsed = 0;
        }
    }
    Iterator iterator = tree.cursorAt(new Key(new byte[1]));
    long then = System.nanoTime();
    while (iterator.hasNext()) {
        iterator.next();
    }
    long elapsed = System.nanoTime() - then;
    System.out
            .println("Cursor can read " + (((double) howMany / (double) elapsed) * 1000000000d) + " keys/sec");
}

From source file:org.cocos2dx.lib.Cocos2dxRenderer.java

public void onSurfaceCreated(GL10 gl, EGLConfig config) {
    nativeInit(screenWidth, screenHeight);
    last = System.nanoTime();
    gl.glClearColor(0, 0, 0, 0);
}