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.clust4j.log.LogTimer.java

@Override
public long nanos() {
    return System.nanoTime() - _nanos;
}

From source file:com.norconex.collector.http.delay.impl.SiteDelay.java

public void delay(long expectedDelayNanos, String url) {
    if (expectedDelayNanos <= 0) {
        return;//from w  w w.java  2 s . c o m
    }
    String site = StringUtils.lowerCase(url.replaceFirst("(.*?//.*?)(/.*)|$]", "$1"));
    SleepState sleepState = null;
    try {
        synchronized (siteLastHitNanos) {
            sleepState = siteLastHitNanos.get(site);
            if (sleepState == null) {
                siteLastHitNanos.put(site, new SleepState());
                return;
            }
            while (sleepState.sleeping) {
                Sleeper.sleepNanos(Math.min(TINY_SLEEP_MS, expectedDelayNanos));
            }
            sleepState.sleeping = true;
        }
        delay(expectedDelayNanos, sleepState.lastHitEpochNanos);
        sleepState.lastHitEpochNanos = System.nanoTime();
    } finally {
        if (sleepState != null) {
            sleepState.sleeping = false;
        }
    }
}

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

@RequestMapping(value = "/file", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ImageSearchResult searchByFile(@RequestParam("image") final MultipartFile file) throws IOException {
    long start = System.nanoTime();
    String fileType = file.getContentType();
    if (fileType.startsWith("image")) {
        BufferedImage image = ImageIO.read(file.getInputStream());
        Set<Image> images = service.search(image);
        long duration = (System.nanoTime() - start) / 1000000L;
        return new ImageSearchResult().setImages(images).setDuration(duration);

    }/*from w  w  w .  j a v a  2s .c  o m*/
    return ImageSearchResult.empty();
}

From source file:com.parse.NetworkQueryController.java

/**
 * Retrieves a list of {@link ParseObject}s that satisfy this query from the source.
 *
 * @return A list of all {@link ParseObject}s obeying the conditions set in this query.
 *///from w  w  w  .j ava  2s. co m
/* package */ <T extends ParseObject> Task<List<T>> findAsync(final ParseQuery.State<T> state,
        String sessionToken, boolean shouldRetry, Task<Void> ct) {
    final long queryStart = System.nanoTime();

    final ParseRESTCommand command = ParseRESTQueryCommand.findCommand(state, sessionToken);
    if (shouldRetry) {
        command.enableRetrying();
    }

    final long querySent = System.nanoTime();
    return command.executeAsync(restClient, ct).onSuccess(new Continuation<JSONObject, List<T>>() {
        @Override
        public List<T> then(Task<JSONObject> task) throws Exception {
            JSONObject json = task.getResult();
            // Cache the results, unless we are ignoring the cache
            ParseQuery.CachePolicy policy = state.cachePolicy();
            if (policy != null && (policy != ParseQuery.CachePolicy.IGNORE_CACHE)) {
                ParseKeyValueCache.saveToKeyValueCache(command.getCacheKey(), json.toString());
            }

            long queryReceived = System.nanoTime();

            List<T> response = convertFindResponse(state, task.getResult());

            long objectsParsed = System.nanoTime();

            if (json.has("trace")) {
                Object serverTrace = json.get("trace");
                PLog.d("ParseQuery",
                        String.format(
                                "Query pre-processing took %f seconds\n" + "%s\n"
                                        + "Client side parsing took %f seconds\n",
                                (querySent - queryStart) / (1000.0f * 1000.0f), serverTrace,
                                (objectsParsed - queryReceived) / (1000.0f * 1000.0f)));
            }
            return response;
        }
    }, Task.BACKGROUND_EXECUTOR);
}

From source file:com.google.dart.tools.designer.model.HtmlRenderHelper.java

/**
 * @return the image of given HTML content, may be <code>null</code>.
 *///  ww w  . j a v a2s. com
public static Image renderImage(final String content) {
    try {
        File tempFile = File.createTempFile("htmlRender", ".html");
        try {
            IOUtils2.writeBytes(tempFile, content.getBytes());
            // start DumpRenderTree
            if (processOutputStream == null) {
                String path;
                {
                    Bundle bundle = DartDesignerPlugin.getDefault().getBundle();
                    URL url = bundle.getEntry("lib/DumpRenderTree.app/Contents/MacOS/DumpRenderTree");
                    path = FileLocator.toFileURL(url).getPath();
                }
                //        ProcessBuilder builder = new ProcessBuilder(path, "-p", tempFile.getAbsolutePath());
                ProcessBuilder builder = new ProcessBuilder(path, "-p", "-");
                builder.redirectErrorStream(true);
                Process process = builder.start();
                processOutputStream = process.getOutputStream();
                processInputStream = process.getInputStream();
                processReader = new BufferedReader(new InputStreamReader(processInputStream));
            }
            long start = System.nanoTime();
            // XXX
            //        processOutputStream.write((tempFile.getAbsolutePath() + "\n").getBytes());
            processOutputStream
                    .write(("http://127.0.0.1:3030/Users/scheglov/dart/dwc_first/web/out/dwc_first.html\n")
                            .getBytes());
            processOutputStream.flush();
            // read tree
            while (true) {
                String line = processReader.readLine();
                System.out.println(line);
                if (line.isEmpty()) {
                    break;
                }
            }
            // read image
            {
                processReader.readLine(); // ActualHash:
                processReader.readLine(); // Content-Type: image/png
                String lengthLine = processReader.readLine(); // Content-Length: 5546
                int pngLength = Integer.parseInt(StringUtils.removeStart(lengthLine, "Content-Length: "));
                //          System.out.println("pngLength: " + pngLength);
                char[] pngChars = new char[pngLength];
                readFully(processReader, pngChars);
                byte[] pngBytes = new String(pngChars).getBytes();
                Image image = new Image(null, new ByteArrayInputStream(pngBytes));
                System.out.println("imageTime: " + (System.nanoTime() - start) / 1000000.0);
                return image;
            }
            //
            //        {
            //          SessionInputBuffer buffer = new AbstractSessionInputBuffer() {
            //            {
            //              init(processInputStream, 1024, new BasicHttpParams());
            //            }
            //
            //            @Override
            //            public boolean isDataAvailable(int timeout) throws IOException {
            //              return false;
            //            }
            //          };
            //          LineParser lineParser = new BasicLineParser(new ProtocolVersion("HTTP", 1, 1));
            //          HttpMessageParser<HttpResponse> parser = new DefaultHttpResponseParser(
            //              buffer,
            //              lineParser,
            //              new DefaultHttpResponseFactory(),
            //              new BasicHttpParams());
            //          HttpResponse response = parser.parse();
            //          System.out.println(response);
            //          HttpParams params = new BasicHttpParams();
            //          SessionInputBuffer inbuffer = new SessionInputBufferMockup(s, "US-ASCII", params);
            //          HttpMessageParser<BasicHttpResponse> parser = new DefaultResponseParser(
            //              inbuffer,
            //              BasicLineParser.DEFAULT,
            //              new DefaultHttpResponseFactory(),
            //              params);
            //
            //          HttpResponse response = parser.parse();
            //        }
            //        while (true) {
            //          String line = processReader.readLine();
            //          System.out.println(line);
            //        }
            //
            //        byte[] bytes = IOUtils2.readBytes(processInputStream);
            //        int exitValue = process.exitValue();
            //        System.out.println("bytes: " + bytes.length);
            //        System.out.println("bytesTime: " + (System.nanoTime() - start) / 1000000.0);
            //        String output = new String(bytes);
            //        System.out.println(StringUtils.substring(output, -10, 0));
            ////        System.out.println(output);
            //        //
            //        int pngOffset = output.indexOf("Content-Type: image/png");
            //        pngOffset = output.indexOf('\n', pngOffset) + 1;
            //        pngOffset = output.indexOf('\n', pngOffset) + 1;
            //        Image image = new Image(null, new ByteArrayInputStream(bytes, pngOffset, bytes.length
            //            - pngOffset));
            //        System.out.println("imageTime: " + (System.nanoTime() - start) / 1000000.0);
            //        return image;
        } finally {
            tempFile.delete();
        }
    } catch (Throwable e) {
        e.printStackTrace();
    }
    return null;
}

From source file:id.ac.idu.common.menu.util.ZkossMenuFactory.java

protected ZkossMenuFactory(Component component) {
    super();/*  w ww .  j  a v  a  2 s . c o  m*/

    this.workspace = UserWorkspace.getInstance();
    assert component != null : "Parent component is null!";
    assert this.workspace != null : "No UserWorkspace exists!";
    long t1 = System.nanoTime();
    this.stack = new LinkedList<Component>();
    push(component);
    createMenu(MetaMenuFactory.getRootMenuDomain().getItems());
}

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

@Test
public void proxyRemoteArtifact() throws Exception {
    byte[] data = ("This is a test: " + System.nanoTime()).getBytes();
    final InputStream stream = new ByteArrayInputStream(data);
    final String path = "org/foo/foo-project/1/foo-1.txt";
    server.expect(server.formatUrl(STORE, path), 200, stream);

    client.stores().create(new RemoteRepository(STORE, server.formatUrl(STORE)), "adding test proxy",
            RemoteRepository.class);

    try (HttpResources httpResources = client.module(IndyRawHttpModule.class).getHttp()
            .getRaw(client.content().contentPath(remote, STORE, path))) {
        HttpResponse response = httpResources.getResponse();

        String contentLength = response.getFirstHeader("Content-Length").getValue();
        assertThat("Wrong content-length for download: " + contentLength + " (should have been: " + data.length
                + ")", contentLength, equalTo(Integer.toString(data.length)));
    }/*from  ww w  .j  av  a 2 s. c o  m*/

    final PathInfo result = client.content().getInfo(remote, STORE, path);

    assertThat("no result", result, notNullValue());
    assertThat("doesn't exist", result.exists(), equalTo(true));
}

From source file:com.ibm.bi.dml.runtime.controlprogram.parfor.RemoteDPParForSpark.java

/**
 * //ww w .j  a va  2 s.  co  m
 * @param pfid
 * @param program
 * @param taskFile
 * @param resultFile
 * @param enableCPCaching 
 * @param mode
 * @param numMappers
 * @param replication
 * @return
 * @throws DMLRuntimeException
 * @throws DMLUnsupportedOperationException 
 */
public static RemoteParForJobReturn runJob(long pfid, String itervar, String matrixvar, String program,
        String resultFile, MatrixObject input, ExecutionContext ec, PDataPartitionFormat dpf, OutputInfo oi,
        boolean tSparseCol, //config params
        boolean enableCPCaching, int numReducers) //opt params
        throws DMLRuntimeException, DMLUnsupportedOperationException {
    String jobname = "ParFor-DPESP";
    long t0 = DMLScript.STATISTICS ? System.nanoTime() : 0;

    SparkExecutionContext sec = (SparkExecutionContext) ec;
    JavaSparkContext sc = sec.getSparkContext();

    //prepare input parameters
    MatrixDimensionsMetaData md = (MatrixDimensionsMetaData) input.getMetaData();
    MatrixCharacteristics mc = md.getMatrixCharacteristics();
    InputInfo ii = InputInfo.BinaryBlockInputInfo;

    //initialize accumulators for tasks/iterations
    Accumulator<Integer> aTasks = sc.accumulator(0);
    Accumulator<Integer> aIters = sc.accumulator(0);

    JavaPairRDD<MatrixIndexes, MatrixBlock> in = sec.getBinaryBlockRDDHandleForVariable(matrixvar);
    DataPartitionerRemoteSparkMapper dpfun = new DataPartitionerRemoteSparkMapper(mc, ii, oi, dpf);
    RemoteDPParForSparkWorker efun = new RemoteDPParForSparkWorker(program, matrixvar, itervar, enableCPCaching,
            mc, tSparseCol, dpf, oi, aTasks, aIters);
    List<Tuple2<Long, String>> out = in.flatMapToPair(dpfun) //partition the input blocks
            .groupByKey(numReducers) //group partition blocks                 
            .mapPartitionsToPair(efun) //execute parfor tasks, incl cleanup
            .collect(); //get output handles

    //de-serialize results
    LocalVariableMap[] results = RemoteParForUtils.getResults(out, LOG);
    int numTasks = aTasks.value(); //get accumulator value
    int numIters = aIters.value(); //get accumulator value

    //create output symbol table entries
    RemoteParForJobReturn ret = new RemoteParForJobReturn(true, numTasks, numIters, results);

    //maintain statistics
    Statistics.incrementNoOfCompiledSPInst();
    Statistics.incrementNoOfExecutedSPInst();
    if (DMLScript.STATISTICS) {
        Statistics.maintainCPHeavyHitters(jobname, System.nanoTime() - t0);
    }

    return ret;
}

From source file:com.google.jenkins.plugins.credentials.oauth.P12ServiceAccountConfigTestUtil.java

private static File getTempFolder() throws IOException {
    if (tempFolder == null) {
        tempFolder = File.createTempFile("temp", Long.toString(System.nanoTime()));
        if (!tempFolder.delete()) {
            throw new IOException("Could not delete temp file: " + tempFolder.getAbsolutePath());
        }/*from ww  w .jav  a2 s  .  com*/
        if (!tempFolder.mkdir()) {
            throw new IOException("Could not create temp directory: " + tempFolder.getAbsolutePath());
        }
        tempFolder.deleteOnExit();
    }
    return tempFolder;
}

From source file:com.hazelcast.qasonar.utils.GitHubUtils.java

public static String getFileContentsFromGitHub(GHRepository repo, String fileName) throws IOException {
    long started = System.nanoTime();
    try {/*from   ww  w  .ja  v a 2 s. c  o  m*/
        IOException exception = null;
        for (int i = 0; i < GITHUB_FILE_DOWNLOAD_RETRIES; i++) {
            try {
                GHContent fileContent = repo.getFileContent(fileName);

                StringWriter writer = new StringWriter();
                copy(fileContent.read(), writer);

                return writer.toString();
            } catch (FileNotFoundException e) {
                throw e;
            } catch (IOException e) {
                exception = e;
            }
            sleepMillis(GITHUB_EXCEPTION_DELAY_MILLIS * (i + 1));
        }
        throw exception;
    } finally {
        record(TimeTrackerLabel.GET_FILE_CONTENTS_FROM_GITHUB, System.nanoTime() - started);
    }
}