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:co.marcin.novaguilds.manager.PlayerManager.java

public void save() {
    long startTime = System.nanoTime();
    int count = getResourceManager().save(getPlayers());
    LoggerUtils.info("Players data saved in "
            + TimeUnit.MILLISECONDS.convert((System.nanoTime() - startTime), TimeUnit.NANOSECONDS) / 1000.0
            + "s (" + count + " players)");

    startTime = System.nanoTime();
    count = getResourceManager().executeRemoval();
    LoggerUtils.info("Players removed in "
            + TimeUnit.MILLISECONDS.convert((System.nanoTime() - startTime), TimeUnit.NANOSECONDS) / 1000.0
            + "s (" + count + " players)");
}

From source file:com.cloudera.oryx.app.serving.als.LoadBenchmark.java

@Test
public void testRecommendLoad() throws Exception {
    AtomicLong count = new AtomicLong();
    Mean meanReqTimeMS = new Mean();
    long start = System.currentTimeMillis();

    int workers = LoadTestALSModelFactory.WORKERS;
    ExecUtils.doInParallel(workers, workers, true, i -> {
        RandomGenerator random = RandomManager.getRandom(Integer.toString(i).hashCode() ^ System.nanoTime());
        for (int j = 0; j < LoadTestALSModelFactory.REQS_PER_WORKER; j++) {
            String userID = "U" + random.nextInt(LoadTestALSModelFactory.USERS);
            long callStart = System.currentTimeMillis();
            target("/recommend/" + userID).request().accept(MediaType.APPLICATION_JSON_TYPE)
                    .get(LIST_ID_VALUE_TYPE);
            long timeMS = System.currentTimeMillis() - callStart;
            synchronized (meanReqTimeMS) {
                meanReqTimeMS.increment(timeMS);
            }/*from w  w  w .j  a v a2  s  .c o  m*/
            long currentCount = count.incrementAndGet();
            if (currentCount % 100 == 0) {
                log(currentCount, meanReqTimeMS, start);
            }
        }
    });

    int totalRequests = workers * LoadTestALSModelFactory.REQS_PER_WORKER;
    log(totalRequests, meanReqTimeMS, start);
}

From source file:no.kantega.kwashc.server.test.UnvalidatedRedirectTest.java

@Override
protected TestResult testSite(Site site, TestResult testResult) throws Throwable {
    long startTime = System.nanoTime();
    DefaultHttpClient httpclient = new DefaultHttpClient();
    String responseBody = "";

    try {//from   ww w  .j a  va 2s. com
        HttpGet request = new HttpGet(site.getAddress() + "/redirect?url=http://www.internetlastpage.com");
        HttpResponse response = httpclient.execute(request);
        HttpEntity entity = response.getEntity();
        responseBody = EntityUtils.toString(entity);

        // OBS: In case we are sent to the front page, we must check for something more specific than the wprd Kantega
        if (responseBody.contains("very last")) {
            testResult.setResultEnum(ResultEnum.failed);
            testResult.setMessage("The blog can be used in phishing attacks, since it has a redirect service "
                    + "which doesn't discriminate what URLs it redirects to. An attacker might trick a victim into "
                    + "thinking he's visiting your trusted blog, while in reality being forwarded to something "
                    + "malicious.");
        } else {
            testResult.setResultEnum(ResultEnum.passed);
            testResult.setMessage("Ok, your application validates redirects properly.");
        }
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    setDuration(testResult, startTime);
    return testResult;
}

From source file:edu.indiana.d2i.htrc.io.index.solr.SequentialVectorFromSolr.java

@Override
public int run(String[] args) throws Exception {
    if (args.length != 4) {
        printUsage();// w w  w .j  a v  a 2s. c  o  m
    }

    String solrURL = args[0];
    String dictionaryFile = args[1];
    String idsFile = args[2];
    String outputFile = args[3];

    logger.info("SequentialVectorFromSolr ");
    logger.info(" - solrURL: " + solrURL);
    logger.info(" - dictionaryFile: " + dictionaryFile);
    logger.info(" - idsFile: " + idsFile); // on HDFS
    logger.info(" - outputFile: " + outputFile); // on HDFS

    Configuration conf = getConf();
    //      conf.set(HTRCConstants.SOLR_MAIN_URL, solrURL);
    conf.set("htrc.solr.url", solrURL);
    conf.set(HTRCConstants.DICTIONARY_PATH, dictionaryFile);

    SolrClient client = new SolrClient(conf, true);
    FileSystem fs = FileSystem.get(conf);

    SequenceFile.Writer writer = new SequenceFile.Writer(fs, conf, new Path(outputFile), Text.class,
            VectorWritable.class);

    long t0 = System.nanoTime();
    DataInputStream fsinput = new DataInputStream(fs.open(new Path(idsFile)));
    BufferedReader reader = new BufferedReader(new InputStreamReader(fsinput));
    String line = null;
    String[] ids = new String[1];
    VectorWritable value = new VectorWritable();
    Text key = new Text();
    int count = 0;
    while ((line = reader.readLine()) != null) {
        ids[0] = line;
        Iterable<NamedVector> termVectors = client.getTermVectors(ids);
        for (NamedVector namedVector : termVectors) {
            value.set(namedVector);
            key.set(namedVector.getName());
            writer.append(key, value);
            count++;
        }
        if (count % 1000 == 0)
            System.out.println("Finish " + count + " volumes.");
    }
    long t1 = System.nanoTime();
    System.out.println("Takes " + (t1 - t0) / 1e9 + " seconds");

    writer.close();
    reader.close();

    return 0;
}

From source file:com.proofpoint.stats.TimedStat.java

public <T> T time(Callable<T> callable) throws Exception {
    long start = System.nanoTime();
    T result = callable.call();//  www .  java2 s .co m
    addValue(Duration.nanosSince(start));
    return result;
}

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

/**
 * {@inheritDoc}/*from  w  ww.  j a v a  2  s . c o m*/
 */
@Override
public void executeTask(@NotNull final Map<String, Object> context) throws GenieException, IOException {
    final Set<Tag> tags = Sets.newHashSet();
    final long start = System.nanoTime();
    try {
        final JobExecutionEnvironment jobExecEnv = (JobExecutionEnvironment) context
                .get(JobConstants.JOB_EXECUTION_ENV_KEY);
        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 Application Task for job {}",
                jobExecEnv.getJobRequest().getId().orElse(NO_ID_FOUND));

        for (final Application application : jobExecEnv.getApplications()) {
            final long applicationStart = System.nanoTime();
            final Set<Tag> applicationTags = Sets.newHashSet();
            applicationTags.add(Tag.of(MetricsConstants.TagKeys.APPLICATION_ID, application.getId()));
            applicationTags.add(
                    Tag.of(MetricsConstants.TagKeys.APPLICATION_NAME, application.getMetadata().getName()));

            try {
                final String applicationId = application.getId();

                // Create the directory for this application under applications in the cwd
                createEntityInstanceDirectory(genieDir, applicationId, AdminResources.APPLICATION);

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

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

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

                        super.generateSetupFileSourceSnippet(applicationId, "Application:", localPath, writer,
                                jobWorkingDirectory);
                    }
                }

                // Iterate over and get all dependencies
                for (final String dependencyFile : application.getResources().getDependencies()) {
                    final String localPath = super.buildLocalFilePath(jobWorkingDirectory, applicationId,
                            dependencyFile, FileType.DEPENDENCIES, AdminResources.APPLICATION);
                    fts.getFile(dependencyFile, localPath);
                }

                // Iterate over and get all configuration files
                for (final String configFile : application.getResources().getConfigs()) {
                    final String localPath = super.buildLocalFilePath(jobWorkingDirectory, applicationId,
                            configFile, FileType.CONFIG, AdminResources.APPLICATION);
                    fts.getFile(configFile, localPath);
                }
                MetricsUtils.addSuccessTags(applicationTags);
            } catch (Throwable t) {
                MetricsUtils.addFailureTagsWithException(applicationTags, t);
                throw t;
            } finally {
                final long applicationFinish = System.nanoTime();
                this.getRegistry().timer(APPLICATION_SETUP_TIMER_NAME, applicationTags)
                        .record(applicationFinish - applicationStart, TimeUnit.NANOSECONDS);
            }
        }
        log.info("Finished Application Task for job {}",
                jobExecEnv.getJobRequest().getId().orElse(NO_ID_FOUND));
        MetricsUtils.addSuccessTags(tags);
    } catch (final Throwable t) {
        MetricsUtils.addFailureTagsWithException(tags, t);
        throw t;
    } finally {
        this.getRegistry().timer(APPLICATION_TASK_TIMER_NAME, tags).record(System.nanoTime() - start,
                TimeUnit.NANOSECONDS);
    }
}

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

/**
 * {@inheritDoc}//from   w w w  .  java 2s.c  om
 */
@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 String jobWorkingDirectory = jobExecEnv.getJobWorkingDir().getCanonicalPath();
        final Writer writer = (Writer) context.get(JobConstants.WRITER_KEY);
        final String jobId = jobExecEnv.getJobRequest().getId()
                .orElseThrow(() -> new GeniePreconditionException("No job id found. Unable to continue"));
        log.info("Starting Job Task for job {}", jobId);

        final Optional<String> setupFile = jobExecEnv.getJobRequest().getSetupFile();
        if (setupFile.isPresent()) {
            final String jobSetupFile = setupFile.get();
            if (StringUtils.isNotBlank(jobSetupFile)) {
                final String localPath = jobWorkingDirectory + JobConstants.FILE_PATH_DELIMITER + jobSetupFile
                        .substring(jobSetupFile.lastIndexOf(JobConstants.FILE_PATH_DELIMITER) + 1);

                fts.getFile(jobSetupFile, localPath);

                writer.write("# Sourcing setup file specified in job request" + System.lineSeparator());
                writer.write(
                        JobConstants.SOURCE
                                + localPath.replace(jobWorkingDirectory,
                                        "${" + JobConstants.GENIE_JOB_DIR_ENV_VAR + "}")
                                + System.lineSeparator());

                // Append new line
                writer.write(System.lineSeparator());
            }
        }

        // Iterate over and get all configs and dependencies
        final Collection<String> configsAndDependencies = Sets.newHashSet();
        configsAndDependencies.addAll(jobExecEnv.getJobRequest().getDependencies());
        configsAndDependencies.addAll(jobExecEnv.getJobRequest().getConfigs());
        for (final String dependentFile : configsAndDependencies) {
            if (StringUtils.isNotBlank(dependentFile)) {
                final String localPath = jobWorkingDirectory + JobConstants.FILE_PATH_DELIMITER + dependentFile
                        .substring(dependentFile.lastIndexOf(JobConstants.FILE_PATH_DELIMITER) + 1);

                fts.getFile(dependentFile, localPath);
            }
        }

        // Copy down the attachments if any to the current working directory
        this.attachmentService.copy(jobId, jobExecEnv.getJobWorkingDir());
        // Delete the files from the attachment service to save space on disk
        this.attachmentService.delete(jobId);

        // Print out the current Envrionment to a env file before running the command.
        writer.write("# Dump the environment to a env.log file" + System.lineSeparator());
        writer.write("env | sort > " + "${" + JobConstants.GENIE_JOB_DIR_ENV_VAR + "}"
                + JobConstants.GENIE_ENV_PATH + System.lineSeparator());

        // Append new line
        writer.write(System.lineSeparator());

        writer.write("# Kick off the command in background mode and wait for it using its pid"
                + System.lineSeparator());

        writer.write(StringUtils.join(jobExecEnv.getCommand().getExecutable(), StringUtils.SPACE)
                + JobConstants.WHITE_SPACE + jobExecEnv.getJobRequest().getCommandArgs().orElse(EMPTY_STRING)
                + JobConstants.STDOUT_REDIRECT + "${" + JobConstants.GENIE_JOB_DIR_ENV_VAR + "}/"
                + JobConstants.STDOUT_LOG_FILE_NAME + JobConstants.STDERR_REDIRECT + "${"
                + JobConstants.GENIE_JOB_DIR_ENV_VAR + "}/" + JobConstants.STDERR_LOG_FILE_NAME + " &"
                + System.lineSeparator());

        // Save PID of children process, used in trap handlers to kill and verify termination
        writer.write(JobConstants.EXPORT + JobConstants.CHILDREN_PID_ENV_VAR + "=$!" + System.lineSeparator());
        // Wait for the above process started in background mode. Wait lets us get interrupted by kill signals.
        writer.write("wait ${" + JobConstants.CHILDREN_PID_ENV_VAR + "}" + System.lineSeparator());

        // Append new line
        writer.write(System.lineSeparator());

        // capture exit code and write to temporary genie.done
        writer.write("# Write the return code from the command in the done file." + System.lineSeparator());
        writer.write(JobConstants.GENIE_DONE_FILE_CONTENT_PREFIX + "${" + JobConstants.GENIE_JOB_DIR_ENV_VAR
                + "}" + "/" + JobConstants.GENIE_TEMPORARY_DONE_FILE_NAME + System.lineSeparator());

        // atomically swap temporary and actual genie.done file if one doesn't exist
        writer.write(
                "# Swapping done file, unless one exist created by trap handler." + System.lineSeparator());
        writer.write("mv -n " + "${" + JobConstants.GENIE_JOB_DIR_ENV_VAR + "}" + "/"
                + JobConstants.GENIE_TEMPORARY_DONE_FILE_NAME + " " + "${" + JobConstants.GENIE_JOB_DIR_ENV_VAR
                + "}" + "/" + JobConstants.GENIE_DONE_FILE_NAME + System.lineSeparator());

        // Print the timestamp once its done running.
        writer.write("echo End: `date '+%Y-%m-%d %H:%M:%S'`\n");

        log.info("Finished Job Task for job {}", jobId);
        MetricsUtils.addSuccessTags(tags);
    } catch (final Throwable t) {
        MetricsUtils.addFailureTagsWithException(tags, t);
        throw t;
    } finally {
        this.getRegistry().timer(JOB_TASK_TIMER_NAME, tags).record(System.nanoTime() - start,
                TimeUnit.NANOSECONDS);
    }
}

From source file:com.alexkli.jhb.Worker.java

@Override
public void run() {
    try {/*  w  ww . j a v  a2s  .c o m*/
        while (true) {
            long start = System.nanoTime();

            QueueItem<HttpRequestBase> item = queue.take();

            idleAvg.add(System.nanoTime() - start);

            if (item.isPoisonPill()) {
                return;
            }

            HttpRequestBase request = item.getRequest();

            if ("java".equals(config.client)) {
                System.setProperty("http.keepAlive", "false");

                item.sent();

                try {
                    HttpURLConnection http = (HttpURLConnection) new URL(request.getURI().toString())
                            .openConnection();
                    http.setConnectTimeout(5000);
                    http.setReadTimeout(5000);
                    int statusCode = http.getResponseCode();

                    consumeAndCloseStream(http.getInputStream());

                    if (statusCode == 200) {
                        item.done();
                    } else {
                        item.failed();
                    }
                } catch (IOException e) {
                    System.err.println("Failed request: " + e.getMessage());
                    e.printStackTrace();
                    //                        System.exit(2);
                    item.failed();
                }
            } else if ("ahc".equals(config.client)) {
                try {
                    item.sent();

                    try (CloseableHttpResponse response = httpClient.execute(request, context)) {
                        int statusCode = response.getStatusLine().getStatusCode();
                        if (statusCode == 200) {
                            item.done();
                        } else {
                            item.failed();
                        }
                    }
                } catch (IOException e) {
                    System.err.println("Failed request: " + e.getMessage());
                    item.failed();
                }
            } else if ("fast".equals(config.client)) {
                try {
                    URI uri = request.getURI();

                    item.sent();

                    InetAddress addr = InetAddress.getByName(uri.getHost());
                    Socket socket = new Socket(addr, uri.getPort());
                    PrintWriter out = new PrintWriter(socket.getOutputStream());
                    //                        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    // send an HTTP request to the web server
                    out.println("GET / HTTP/1.1");
                    out.append("Host: ").append(uri.getHost()).append(":").println(uri.getPort());
                    out.println("Connection: Close");
                    out.println();
                    out.flush();

                    // read the response
                    consumeAndCloseStream(socket.getInputStream());
                    //                        boolean loop = true;
                    //                        StringBuilder sb = new StringBuilder(8096);
                    //                        while (loop) {
                    //                            if (in.ready()) {
                    //                                int i = 0;
                    //                                while (i != -1) {
                    //                                    i = in.read();
                    //                                    sb.append((char) i);
                    //                                }
                    //                                loop = false;
                    //                            }
                    //                        }
                    item.done();
                    socket.close();

                } catch (IOException e) {
                    e.printStackTrace();
                    item.failed();
                }
            } else if ("nio".equals(config.client)) {
                URI uri = request.getURI();

                item.sent();

                String requestBody = "GET / HTTP/1.1\n" + "Host: " + uri.getHost() + ":" + uri.getPort() + "\n"
                        + "Connection: Close\n\n";

                try {
                    InetSocketAddress addr = new InetSocketAddress(uri.getHost(), uri.getPort());
                    SocketChannel channel = SocketChannel.open();
                    channel.socket().setSoTimeout(5000);
                    channel.connect(addr);

                    ByteBuffer msg = ByteBuffer.wrap(requestBody.getBytes());
                    channel.write(msg);
                    msg.clear();

                    ByteBuffer buf = ByteBuffer.allocate(1024);

                    int count;
                    while ((count = channel.read(buf)) != -1) {
                        buf.flip();

                        byte[] bytes = new byte[count];
                        buf.get(bytes);

                        buf.clear();
                    }
                    channel.close();

                    item.done();

                } catch (IOException e) {
                    e.printStackTrace();
                    item.failed();
                }
            }
        }
    } catch (InterruptedException e) {
        System.err.println("Worker thread [" + this.toString() + "] was interrupted: " + e.getMessage());
    }
}

From source file:com.garyclayburg.persistence.repository.UserStore.java

@CrossOrigin(origins = "*")
@RequestMapping(value = "/findByFirstname", method = RequestMethod.GET)
public @ResponseBody User findByFirstname(
        @RequestParam(value = "firstname", required = true) String firstname) {
    log.info("looking for firstname " + firstname);
    long start = System.nanoTime();
    User byFirstname = autoUserRepo.findByFirstname(firstname);
    log.debug(/*from w  ww.j  a  v a 2s  .c o  m*/
            "           found user " + firstname + " " + (System.nanoTime() - start) / 1000 + " microseconds");
    return byFirstname;
}

From source file:no.kantega.kwashc.server.test.FailureToRestrictUrlTest.java

@Override
protected TestResult testSite(Site site, TestResult testResult) throws Throwable {
    long startTime = System.nanoTime();
    DefaultHttpClient httpclient = new DefaultHttpClient();
    String responseBody = "";

    try {/*  w  w  w  . j a  va2  s. co m*/
        HttpGet request = new HttpGet(site.getAddress() + "/blog/admin?commentToDelete"
                + "=00121212123123123123123123123123123343435436456745675647456564444444454554");
        HttpResponse response = httpclient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        responseBody = EntityUtils.toString(entity);
        String generalError = "Your application fails to restrict privileged URLs properly!";

        if (statusCode == 500) {
            testResult.setResultEnum(ResultEnum.failed);
            testResult.setMessage(generalError);
        } else if (statusCode == 404) {
            testResult.setResultEnum(ResultEnum.passed);
            testResult.setMessage(
                    "Your application restricts URLs properly, but can you be sure no one was using "
                            + "/blog/admin?");
        } else if (statusCode == 200 && responseBody.contains("You asked for a protected resource")) {
            testResult.setResultEnum(ResultEnum.passed);
            testResult.setMessage("Your application restricts URLs properly!");
        } else {
            testResult.setResultEnum(ResultEnum.failed);
            testResult.setMessage(generalError);
        }
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    setDuration(testResult, startTime);
    return testResult;
}