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.elasticsearch.xpack.watcher.common.http.HttpConnectionTimeoutTests.java

@Network
public void testDefaultTimeoutCustom() throws Exception {
    Environment environment = TestEnvironment
            .newEnvironment(Settings.builder().put("path.home", createTempDir()).build());
    HttpClient httpClient = new HttpClient(
            Settings.builder().put("xpack.http.default_connection_timeout", "5s").build(),
            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  ww  . j  a  v  a 2 s.co 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 7, but we'll give it an error margin of 2 seconds
        assertThat(timeout.seconds(), greaterThan(3L));
        assertThat(timeout.seconds(), lessThan(7L));
        // expected
    }
}

From source file:metlos.executors.batch.BatchCpuThrottlingExecutorTest.java

@Test
public void maxUsage_SingleThreaded() throws Exception {
    NamingThreadFactory factory = new NamingThreadFactory();
    ThreadPoolExecutor e = new ThreadPoolExecutor(1, 1, 0, TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>(),
            factory);/* ww  w .ja v a 2s  .  c  o  m*/
    e.prestartAllCoreThreads();

    List<Future<?>> payloadResults = new ArrayList<Future<?>>();

    long startTime = System.nanoTime();

    //create load
    for (int i = 0; i < NOF_JOBS; ++i) {
        Future<?> f = e.submit(new Payload());
        payloadResults.add(f);
    }

    //wait for it all to finish
    for (Future<?> f : payloadResults) {
        f.get();
    }

    long endTime = System.nanoTime();

    long time = endTime - startTime;
    LOG.info("MAX Singlethreaded test took " + (time / 1000.0 / 1000.0) + "ms");

    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    long cpuTime = 0;
    for (Thread t : factory.createdThreads) {
        long threadCpuTime = threadBean.getThreadCpuTime(t.getId());
        LOG.info(t.getName() + ": " + threadCpuTime + "ns");
        cpuTime += threadCpuTime;
    }

    float actualUsage = (float) cpuTime / time;

    LOG.info("MAX Singlethreaded overall usage: " + actualUsage);
}

From source file:com.codenvy.cas.adaptors.ldap.services.DefaultLdapRegisteredServiceMapper.java

@Override
public LdapEntry mapFromRegisteredService(final String dn, final RegisteredService svc) {
    try {/*from  w ww  .  jav a 2 s. c  o m*/
        if (svc.getId() == RegisteredService.INITIAL_IDENTIFIER_VALUE) {
            ((AbstractRegisteredService) svc).setId(System.nanoTime());
        }
        final String newDn = getDnForRegisteredService(dn, svc);
        LOGGER.debug("Creating entry {}", newDn);

        final Collection<LdapAttribute> attrs = new ArrayList<>();
        attrs.add(new LdapAttribute(this.idAttribute, String.valueOf(svc.getId())));

        final StringWriter writer = new StringWriter();
        this.jsonSerializer.toJson(writer, svc);
        attrs.add(new LdapAttribute(this.serviceDefinitionAttribute, writer.toString()));
        attrs.add(new LdapAttribute(LdapUtils.OBJECTCLASS_ATTRIBUTE, "top", this.objectClass));

        return new LdapEntry(newDn, attrs);
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:example.app.service.CustomerService.java

protected long newId() {
    return System.nanoTime();
}

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

private void runJavaAndHessian() {
    while (running) {
        Object requestObject = new RequestObject(requestSize);
        long beginTime = System.nanoTime();
        if (beginTime >= endTime) {
            running = false;//from  w w w .j a va2s.  c o m
            break;
        }
        try {
            Object response = null;
            response = clientFactory.get(targetIP, targetPort, rpcTimeout, clientNums).request(requestObject)
                    .get();
            long currentTime = System.nanoTime();
            if (beginTime <= startTime) {
                continue;
            }
            long consumeTime = currentTime - beginTime;
            sumResponseTimeSpread(consumeTime);
            int range = Integer.parseInt(String.valueOf(beginTime - startTime)) / 1000;
            if (range >= maxRange) {
                System.err.println(
                        "benchmark range exceeds maxRange,range is: " + range + ",maxRange is: " + maxRange);
                continue;
            }
            if (((ResponseObject) response).getBytes() != null) {
                tps[range] = tps[range] + 1;
                responseTimes[range] = responseTimes[range] + consumeTime;
            } else {
                LOGGER.error("server return response 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();
            if (beginTime <= startTime) {
                continue;
            }
            long consumeTime = currentTime - beginTime;
            sumResponseTimeSpread(consumeTime);
            int range = Integer.parseInt(String.valueOf(beginTime - startTime)) / 1000;
            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.scaleoutsoftware.soss.hserver.DatasetRecordReader.java

/**
 * This method chooses current record reader (caching or replaying) based on the information in the split.
 *///from ww w.  ja v a  2 s  .c  om
@Override
public void initialize(InputSplit inputSplit, TaskAttemptContext taskAttemptContext)
        throws IOException, InterruptedException {

    numberOfRecors = 0;
    if (!(inputSplit instanceof ImageInputSplit)) {
        throw new IOException("Unexpected split type: " + inputSplit);
    }
    if (!((ImageInputSplit) inputSplit).isRecorded()) {
        currentRecordReader = cachingRecordReader;
    } else {
        currentRecordReader = replayingRecordReader;
    }

    initialize = System.nanoTime();
    currentRecordReader.initialize(inputSplit, taskAttemptContext);

}

From source file:edu.umass.cs.gigapaxos.paxosutil.PaxosPacketDemultiplexer.java

/**
 * @param json//from w w w .  java  2 s  .co m
 * @param unstringer
 * @return PaxosPacket parsed from JSON.
 * @throws JSONException
 */
public static PaxosPacket toPaxosPacket(JSONObject json, Stringifiable<?> unstringer) throws JSONException {
    PaxosPacket.PaxosPacketType type = PaxosPacket.getPaxosPacketType(json);
    if (type == null)
        fatal(json);

    PaxosPacket paxosPacket = null;
    switch (type) {
    case REQUEST:
        paxosPacket = (new RequestPacket(json));
        break;
    case PROPOSAL:
        paxosPacket = (new ProposalPacket(json));
        break;
    case DECISION:
        paxosPacket = (new PValuePacket(json));
        break;
    case BATCHED_COMMIT:
        paxosPacket = (new BatchedCommit(json));
        break;
    case PREPARE:
        paxosPacket = (new PreparePacket(json));
        break;
    case PREPARE_REPLY:
        paxosPacket = (new PrepareReplyPacket(json));
        break;
    case ACCEPT:
        paxosPacket = (new AcceptPacket(json));
        break;
    case BATCHED_ACCEPT:
        paxosPacket = (new BatchedAccept(json));
        break;
    case BATCHED_PAXOS_PACKET:
        paxosPacket = (new BatchedPaxosPacket(json));
        break;
    case ACCEPT_REPLY:
        paxosPacket = (new AcceptReplyPacket(json));
        break;
    case BATCHED_ACCEPT_REPLY:
        long t = System.nanoTime();
        paxosPacket = (new BatchedAcceptReply(json));
        if (PaxosMessenger.INSTRUMENT_SERIALIZATION && Util.oneIn(100))
            DelayProfiler.updateDelayNano("batchedAcceptReplyPacketization", t,
                    ((BatchedAcceptReply) paxosPacket).size());
        break;
    case SYNC_DECISIONS_REQUEST:
        paxosPacket = (new SyncDecisionsPacket(json));
        break;
    case CHECKPOINT_STATE:
        paxosPacket = (new StatePacket(json));
        break;
    case FAILURE_DETECT:
        assert (unstringer != null);
        paxosPacket = new FailureDetectionPacket<>(json, unstringer);
        break;
    case FIND_REPLICA_GROUP:
        paxosPacket = new FindReplicaGroupPacket(json);
        break;
    default:
        fatal(json);
    }
    assert (paxosPacket != null) : json;
    return paxosPacket;
}

From source file:com.moz.fiji.mapreduce.IntegrationTestFijiBulkLoad.java

/**
 * Generates a random HDFS path.//  w  w w  . j a  v a 2 s. com
 *
 * @param prefix Prefix for the random file name.
 * @return a random HDFS path.
 * @throws Exception on error.
 */
private Path makeRandomPath(String prefix) throws Exception {
    Preconditions.checkNotNull(mFS);
    final Path base = new Path(FileSystem.getDefaultUri(mConf));
    final Random random = new Random(System.nanoTime());
    return new Path(base, String.format("/%s-%s", prefix, random.nextLong()));
}

From source file:test.other.T_DaoTest.java

public void test2() throws SQLException, IOException {
    System.out.println(System.nanoTime() / 1000000);
    ResultSet rs = conn.createStatement().executeQuery("select content from fc_Post where id = 15");
    rs.next();//from  w  ww.  j ava  2 s .  c  om
    String text = rs.getString(1);
    System.out.println(text.length());
    System.out.println(System.nanoTime() / 1000000);
    @SuppressWarnings("resource")
    FileChannel rwChannel = new RandomAccessFile("textfile.txt", "rw").getChannel();
    ByteBuffer wrBuf = rwChannel.map(FileChannel.MapMode.READ_WRITE, 0, text.length() + 10);
    int lg = text.length() / 1000000;
    int pos = 0;
    byte[] buf = new byte[text.length() / 1000000];
    System.out.println(System.nanoTime() / 1000000);
    for (int i = 0; i < 1000000; i++) {
        System.arraycopy(text.getBytes(), pos, buf, 0, lg);
        wrBuf.put(buf);
        pos += lg;
    }
    System.out.println(System.nanoTime() / 1000000);
    rwChannel.close();
}

From source file:com.alibaba.jstorm.ui.model.pages.HomePage.java

public void generateTables() {
    long start = System.nanoTime();
    try {/*  w  w  w.  ja v  a2  s  .c  o m*/
        LOG.info("ClusterPage init...");
        Map conf = UIUtils.readUiConfig();
        List<Map> uiClusters = ConfigExtension.getUiClusters(conf);
        if (uiClusters == null) {
            return;
        }

        TableData table = new TableData();
        tables.add(table);

        List<String> headers = table.getHeaders();
        List<Map<String, ColumnData>> lines = table.getLines();
        table.setName("Cluster List");

        headers.add(StringUtils.capitalize(UIDef.CLUSTER));
        headers.add(HEADER_ZK_ROOT);
        headers.add(HEADER_ZK_SERVERS);
        headers.add(HEADER_ZK_PORT);

        for (Map cluster : uiClusters) {
            Map<String, ColumnData> line = new HashMap<String, ColumnData>();
            lines.add(line);

            String clusterName = ConfigExtension.getUiClusterName(cluster);
            ColumnData clusterColumn = new ColumnData();
            LinkData linkData = new LinkData();
            linkData.setUrl(UIDef.LINK_TABLE_PAGE);
            linkData.setText(clusterName);
            linkData.addParam(UIDef.PAGE_TYPE, UIDef.PAGE_TYPE_CLUSTER);
            linkData.addParam(UIDef.CLUSTER, clusterName);

            clusterColumn.addLinkData(linkData);

            line.put(StringUtils.capitalize(UIDef.CLUSTER), clusterColumn);

            String zkRoot = ConfigExtension.getUiClusterZkRoot(cluster);
            ColumnData zkRootColumn = new ColumnData();
            zkRootColumn.addText(zkRoot);
            line.put(HEADER_ZK_ROOT, zkRootColumn);

            List<String> servers = ConfigExtension.getUiClusterZkServers(cluster);
            ColumnData zkServerColumn = new ColumnData();
            for (String server : servers) {
                zkServerColumn.addText(server);
            }
            line.put(HEADER_ZK_SERVERS, zkServerColumn);

            String port = String.valueOf(ConfigExtension.getUiClusterZkPort(cluster));
            ColumnData zkPortColumn = new ColumnData();
            zkPortColumn.addText(port);
            line.put(HEADER_ZK_PORT, zkPortColumn);
        }

    } catch (Exception e) {
        LOG.error("Failed to get cluster information:", e);
        throw new RuntimeException(e);
    } finally {
        long end = System.nanoTime();
        UIMetrics.updateHistorgram(this.getClass().getSimpleName(), (end - start) / 1000000.0d);

        LOG.info("Finish ClusterPage");
    }
}