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.graphaware.test.util.TestUtils.java

/**
 * Measure the time of the timed callback.
 *
 * @param timed callback./*  w  w w  .j a  v  a2  s .co  m*/
 * @return time in microseconds
 */
public static long time(Timed timed) {
    long start = System.nanoTime();
    timed.time();
    return (System.nanoTime() - start) / 1000;
}

From source file:com.linkedin.pinot.integration.tests.Pql2CompilerTest.java

private void testQuery(PQLCompiler pql1Compiler, Pql2Compiler pql2Compiler, String pql) {
    try {//from  www  .  j av a 2 s . co m
        //System.out.println(pql);
        long pql1StartTime = System.nanoTime();
        // Skip ones that don't compile with Pinot 1
        JSONObject jsonObject;
        try {
            jsonObject = pql1Compiler.compile(pql);
        } catch (Exception e) {
            return;
        }

        BrokerRequest pqlBrokerRequest = RequestConverter.fromJSON(jsonObject);
        pql1Nanos += (System.nanoTime() - pql1StartTime);
        queryCount++;
        long pql2StartTime = System.nanoTime();
        BrokerRequest pql2BrokerRequest = pql2Compiler.compileToBrokerRequest(pql);
        pql2Nanos += (System.nanoTime() - pql2StartTime);
        Assert.assertTrue(brokerRequestsAreEquivalent(pqlBrokerRequest, pql2BrokerRequest),
                "Requests are not equivalent\npql2: " + pql2BrokerRequest + "\npql: " + pqlBrokerRequest
                        + "\nquery:" + pql);
    } catch (Exception e) {
        Assert.fail("Caught exception compiling " + pql, e);
    }
}

From source file:org.disit.servicemap.SparqlProxy.java

private void redirectToLog(HttpServletRequest theReq, HttpServletResponse theResp) throws Exception {

    HttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = null;/*from w w  w.  j  a  v  a  2 s.  c o m*/
    HttpResponse response = null;

    long startTime = System.nanoTime();

    String theServerHost = Configuration.getInstance().get("sparqlEndpoint", null);
    if (theServerHost == null)
        theServerHost = "http://192.168.0.207:8890/sparql";

    //String aEncodedQuery = URLEncoder.encode(query, "UTF-8");
    //String serviceUri = theReq.getParameter("query");
    String theReqUrl = theServerHost + "?";
    String query = theReq.getParameter("query");
    if (query != null) {
        String aEncodedQuery = URLEncoder.encode(query, "UTF-8");
        theReqUrl += "query=" + aEncodedQuery;
    }
    String format = theReq.getParameter("format");
    if (format != null)
        theReqUrl += "&format=" + format;

    try {
        httpget = new HttpGet(theReqUrl);

        //System.out.println("request header:");
        Enumeration<String> aHeadersEnum = theReq.getHeaderNames();
        while (aHeadersEnum.hasMoreElements()) {
            String aHeaderName = aHeadersEnum.nextElement();
            String aHeaderVal = theReq.getHeader(aHeaderName);
            httpget.setHeader(aHeaderName, aHeaderVal);
            //System.out.println("  " + aHeaderName + ": " + aHeaderVal);
        }

        if (log.isDebugEnabled()) {
            log.debug("executing request " + httpget.getURI());
        }

        // Create a response handler
        response = httpclient.execute(httpget);

        //System.out.println("response header:");
        // set the same Headers
        for (Header aHeader : response.getAllHeaders()) {
            if (!aHeader.getName().equals("Transfer-Encoding") || !aHeader.getValue().equals("chunked")) {
                theResp.setHeader(aHeader.getName(), aHeader.getValue());
            }
            //System.out.println("  " + aHeader.getName() + ": " + aHeader.getValue());
        }

        // set the same locale
        if (response.getLocale() != null) {
            theResp.setLocale(response.getLocale());
        }

        // set the content
        theResp.setContentLength((int) response.getEntity().getContentLength());
        theResp.setContentType(response.getEntity().getContentType().getValue());

        // set the same status
        theResp.setStatus(response.getStatusLine().getStatusCode());

        // redirect the output
        InputStream aInStream = null;
        OutputStream aOutStream = null;
        try {
            aInStream = response.getEntity().getContent();
            aOutStream = theResp.getOutputStream();

            byte[] buffer = new byte[1024];
            int r = 0;
            do {
                r = aInStream.read(buffer);
                if (r != -1) {
                    aOutStream.write(buffer, 0, r);
                }
            } while (r != -1);
            /*
             int data = aInStream.read();
             while (data != -1) {
             aOutStream.write(data);
                    
             data = aInStream.read();
             }
             */
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            if (aInStream != null) {
                aInStream.close();
            }
            if (aOutStream != null) {
                aOutStream.close();
            }
        }
    } finally {
        httpclient.getConnectionManager().closeExpiredConnections();
        httpclient.getConnectionManager().shutdown();
    }
    ServiceMap.logQuery(query, "SPARQL", theReq.getRemoteAddr(), theReq.getHeader("User-Agent"),
            System.nanoTime() - startTime);
}

From source file:hu.vpmedia.media.red5.bwcheck.BandwidthDetection.java

public void calculateClientBw(IConnection p_client) {

    for (int i = 0; i < 1200; i++) {
        payload[i] = Math.random();
    }/*from  w ww  .  ja va2 s. c  om*/

    p_client.setAttribute("payload", payload);

    for (int i = 0; i < 12000; i++) {
        payload_1[i] = Math.random();
    }

    p_client.setAttribute("payload_1", payload_1);

    for (int i = 0; i < 12000; i++) {
        payload_2[i] = Math.random();
    }

    p_client.setAttribute("payload_2", payload_2);

    final IStreamCapableConnection beginningStats = this.getStats();
    final Long start = new Long(System.nanoTime() / 1000000); //new Long(System.currentTimeMillis());

    this.client = p_client;
    beginningValues = new HashMap<String, Long>();
    beginningValues.put("b_down", beginningStats.getWrittenBytes());
    beginningValues.put("b_up", beginningStats.getReadBytes());
    beginningValues.put("time", start);

    this.pakSent.add(start);
    this.sent++;
    log.info("Starting bandwidth check at " + start);
    this.callBWCheck("");

}

From source file:de.htwg_konstanz.in.uce.hp.parallel.integration_test.SourceMock.java

@Override
protected boolean waitForTarget() {
    MediatorBrowser browser = new MediatorBrowser(mediatorAddress);
    long start = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime());
    try {/* w  ww .j  a v  a  2  s.co  m*/
        while ((TimeUnit.NANOSECONDS.toSeconds(System.nanoTime()) - start) <= WAIT_TIME_FOR_TARGET
                && !browser.getSetOfRegisteredTargets().contains(id)) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return false;
            }
        }
        return browser.getSetOfRegisteredTargets().contains(id);
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:org.commonjava.indy.ftest.core.content.NestedStoreInGroupWithErrorTest.java

@Test
public void run() throws Exception {
    final String path = "org/foo/bar/pom.xml";

    final String repo1 = "repo1";
    final String content = "This is a test: " + System.nanoTime();
    final InputStream stream = new ByteArrayInputStream(content.getBytes());
    server.expect(server.formatUrl(repo1, path), 200, stream);
    RemoteRepository remote1 = new RemoteRepository(repo1, server.formatUrl(repo1));
    remote1 = client.stores().create(remote1, "adding remote2", RemoteRepository.class);

    final String repo2 = "repo2";
    server.registerException(server.formatUrl(repo2, path), "upstream error", HttpStatus.SC_UNAUTHORIZED);
    RemoteRepository remote2 = new RemoteRepository(repo2, server.formatUrl(repo2));
    remote2.setMetadata(Location.CONNECTION_TIMEOUT_SECONDS, Integer.toString(1));
    remote2 = client.stores().create(remote2, "adding remote2", RemoteRepository.class);

    final String gName = "test";
    Group tgroup = new Group(gName, Arrays.asList(remote2.getKey(), remote1.getKey()));
    client.stores().create(tgroup, "new group with remote2", Group.class);
    try (InputStream is = client.content().get(group, gName, path)) {
        assertThat(IOUtils.toString(is), equalTo(content));
    }//  ww w.  ja v a 2 s  . co m
}

From source file:com.linkedin.pinot.core.realtime.impl.RealtimeSegmentImplTest.java

@BeforeClass
public void setup() {
    PinotDataBufferMemoryManager memoryManager = new MmapMemoryManager("/tmp", SEGMENT_NAME);
    _configBuilder = new RealtimeSegmentConfig.Builder();
    _random = new Random(System.nanoTime());

    RealtimeSegmentStatsHistory statsHistory = mock(RealtimeSegmentStatsHistory.class);
    when(statsHistory.getEstimatedAvgColSize(any(String.class))).thenReturn(32);
    when(statsHistory.getEstimatedCardinality(any(String.class))).thenReturn(200);

    _configBuilder.setCapacity(1000000).setMemoryManager(memoryManager)
            .setNoDictionaryColumns(new HashSet<>(Collections.singletonList(METRIC_COLUMN))).setOffHeap(true)
            .setSchema(buildSchema()).setSegmentName(SEGMENT_NAME).setStatsHistory(statsHistory)
            .setInvertedIndexColumns(new HashSet<>(Collections.singletonList(DIMENSION_1)))
            .setRealtimeSegmentZKMetadata(new RealtimeSegmentZKMetadata()).setAggregateMetrics(true);
}

From source file:com.hazelcast.simulator.worker.metronome.SimpleMetronome.java

@Override
public void waitForNext() {
    // set random interval on the first run
    if (waitUntil == 0) {
        waitUntil = System.nanoTime() + nextLong(0, intervalNanos);
    }//from   w  w w . j  a  v a 2s.  c o m

    // busy loop
    long now;
    do {
        now = System.nanoTime();
    } while (now < waitUntil);

    // set regular interval for next call
    waitUntil = now + intervalNanos;
}

From source file:net.openhft.chronicle.logger.slf4j.Slf4jVanillaChronicleBinaryLoggerPerfTest.java

@Test
public void testSingleThreadLogging1() throws IOException {
    Thread.currentThread().setName("perf-plain-vanilla");

    final String testId = "perf-binary-vanilla-chronicle";
    final Logger clogger = LoggerFactory.getLogger(testId);
    final long items = 1000000;

    warmup(clogger);//from  www.j a  v  a2  s.  c  om

    for (int s = 64; s <= 1024; s += 64) {
        final String staticStr = StringUtils.leftPad("", s, 'X');

        long cStart1 = System.nanoTime();

        for (int i = 1; i <= items; i++) {
            clogger.info(staticStr);
        }

        long cEnd1 = System.nanoTime();

        System.out.printf("items=%03d size=%04d => chronology=%.3f ms, chronology-average=%.3f us\n", items,
                staticStr.length(), (cEnd1 - cStart1) / 1e6, (cEnd1 - cStart1) / items / 1e3);
    }

    ChronicleTools.deleteOnExit(basePath(testId));
}

From source file:DataBufferGrabber.java

/**
 * Perform and time several drawImage() calls with the given parameters
 * and return the number of milliseconds that the operation took.
 *//* w w  w .  j a  v a  2 s.co  m*/
private long copyImage(Graphics g, BufferedImage image, int x, int y) {
    long startTime = System.nanoTime();
    // Do the operation several times to make the timings more significant
    for (int i = 0; i < 100; ++i) {
        g.drawImage(image, x, y, null);
    }
    // Make sure any graphics commands in hardware get flushed before
    // stopping the clock
    Toolkit.getDefaultToolkit().sync();
    long endTime = System.nanoTime();
    return (endTime - startTime) / 1000000;
}