Example usage for java.util.concurrent TimeUnit NANOSECONDS

List of usage examples for java.util.concurrent TimeUnit NANOSECONDS

Introduction

In this page you can find the example usage for java.util.concurrent TimeUnit NANOSECONDS.

Prototype

TimeUnit NANOSECONDS

To view the source code for java.util.concurrent TimeUnit NANOSECONDS.

Click Source Link

Document

Time unit representing one thousandth of a microsecond.

Usage

From source file:com.github.gfx.android.orma.example.fragment.BenchmarkFragment.java

static long runWithBenchmark(Runnable task) {
    long t0 = System.nanoTime();

    for (int i = 0; i < N_OPS; i++) {
        task.run();/*from  w  w  w . jav a2 s .  c o  m*/
    }

    return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t0);
}

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:hu.bme.mit.trainbenchmark.benchmark.util.BenchmarkResult.java

public long stopClock() {
    stopwatch.stop();
    final long nanos = stopwatch.elapsed(TimeUnit.NANOSECONDS);
    return nanos;
}

From source file:com.webtide.jetty.load.generator.jenkins.LoadGeneratorProcessRunner.java

public void runProcess(TaskListener taskListener, FilePath workspace, Launcher launcher, String jdkName, //
        Node currentNode, List<Resource.NodeListener> nodeListeners, //
        List<LoadGenerator.Listener> loadGeneratorListeners, //
        List<String> args, String jvmExtraArgs, String alpnVersion, //
        Map<String, String> jdkVersionAlpnBootVersions) throws Exception {

    Channel channel = null;//from  w  w w  .  ja  va 2  s .  com

    try {
        long start = System.nanoTime();

        JDK jdk = StringUtils.isEmpty(jdkName) ? //
                null : Jenkins.getInstance().getJDK(jdkName).forNode(currentNode, taskListener);

        channel = new LoadGeneratorProcessFactory().buildChannel(taskListener, jdk, workspace, launcher,
                jvmExtraArgs);

        // alpn version from jdk
        if (StringUtils.isEmpty(alpnVersion) && !StringUtils.equals(alpnVersion, "N/A")) {

            String javaVersion = findJavaVersion(channel, taskListener);
            alpnVersion = jdkVersionAlpnBootVersions.get(javaVersion);
            // download alpn jar
        }

        channel.call(new LoadCaller(args, nodeListeners, loadGeneratorListeners));

        long end = System.nanoTime();

        taskListener.getLogger().println("remote LoadGenerator execution done: " //
                + TimeUnit.NANOSECONDS.toMillis(end - start) //
                + " ms ");
    } finally {
        if (channel != null) {
            channel.close();
        }
    }

}

From source file:at.alladin.rmbt.client.tools.impl.CpuStatCollector.java

public JSONObject getJsonResult(boolean clean, long relTimeStamp, TimeUnit timeUnit) throws JSONException {
    final long relativeTimeStampNs = TimeUnit.NANOSECONDS.convert(relTimeStamp, timeUnit);
    final JSONArray jsonArray = new JSONArray();
    for (CollectorData<Float> data : collectorDataList) {
        final JSONObject dataJson = new JSONObject();
        dataJson.put("value", ((data.getValue() * 100f)));
        dataJson.put("time_ns", data.getTimeStampNs() - relativeTimeStampNs);
        jsonArray.put(dataJson);/*from  w  w  w  .j  a v a 2  s. c  om*/
    }

    final JSONObject jsonObject = new JSONObject();
    if (!cpuStat.getLastCpuUsage().isDetectedIdleOrIoWaitDrop()) {
        jsonObject.put("values", jsonArray);
    } else {
        jsonObject.put("values", new JSONArray());
        final JSONArray flagArray = new JSONArray();
        JSONObject flag = new JSONObject();
        flag.put("info", "implausible idle/iowait");
        flagArray.put(flag);
        jsonObject.put("flags", flagArray);
    }

    if (clean) {
        collectorDataList.clear();
    }

    return jsonObject;
}

From source file:com.flipkart.aesop.runtime.bootstrap.consumer.DefaultBlockingEventConsumer.java

public void shutdown() {
    for (int i = 0; i < numberOfPartition; i++) {
        executors.get(i).shutdown();//  ww w. j ava2s  .co m
    }

    try {
        for (int i = 0; i < numberOfPartition; i++) {
            executors.get(i).awaitTermination(threadTerminationMaxTime, TimeUnit.NANOSECONDS);
        }
    } catch (InterruptedException e) {
        LOGGER.error("Error while stopping bootstrap consumer", e);
    }
}

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  w w  .  j a v a 2 s  . co  m
            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:org.apache.hadoop.hbase.client.AsyncRpcRetryingCaller.java

private long elapsedMs() {
    return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
}

From source file:me.bramhaag.discordselfbot.commands.admin.CommandEvaluate.java

@Command(name = "evaluate", aliases = { "eval", "e" }, minArgs = 1)
public void execute(@NonNull Message message, @NonNull TextChannel channel, @NonNull String[] args) {

    String input = Util.combineArgs(Arrays.copyOfRange(args, 1, args.length));
    Evaluate.Language language = Evaluate.Language.getLanguage(args[0]);

    if (language == null) {
        language = Evaluate.Language.JAVASCRIPT;
        input = Util.combineArgs(args);
    }//from ww w  . ja va 2s .c  om

    input = input.startsWith("```") && input.endsWith("```") ? input.substring(3, input.length() - 3) : input;

    Evaluate.Result result = language.evaluate(Collections.unmodifiableMap(Stream
            .of(ent("jda", message.getJDA()), ent("channel", message.getChannel()),
                    ent("guild", message.getGuild()), ent("msg", message), ent("user", message.getAuthor()),
                    ent("member", message.getGuild().getMember(message.getAuthor())),
                    ent("bot", message.getJDA().getSelfUser()))
            .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue))),
            input);

    message.editMessage(new EmbedBuilder()
            .setTitle("Evaluate " + StringUtils.capitalize(language.name().toLowerCase()), null)
            .addField("Input",
                    new MessageBuilder().appendCodeBlock(input, language.name().toLowerCase()).build()
                            .getRawContent(),
                    true)
            .addField("Output",
                    new MessageBuilder().appendCodeBlock(result.getOutput(), "javascript").build()
                            .getRawContent(),
                    true)
            .setFooter(result.getStopwatch().elapsed(TimeUnit.NANOSECONDS) == 0
                    ? Constants.CROSS_EMOTE + " An error occurred"
                    : String.format(Constants.CHECK_EMOTE + " Took %d ms (%d ns) to complete | %s",
                            result.getStopwatch().elapsed(TimeUnit.MILLISECONDS),
                            result.getStopwatch().elapsed(TimeUnit.NANOSECONDS), Util.generateTimestamp()),
                    null)
            .setColor(color).build()).queue();
}

From source file:org.wso2.carbon.metrics.jdbc.reporter.JdbcReporterTest.java

@BeforeMethod
private void setUp() throws Exception {
    when(clock.getTime()).thenReturn(19910191000L);

    this.reporter = JdbcReporter.forRegistry(registry).convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.NANOSECONDS).withClock(clock).filter(MetricFilter.ALL)
            .build(SOURCE, dataSource);/*w  w w  .ja  v  a  2  s  .c o m*/

    transactionTemplate.execute(status -> {
        template.execute("DELETE FROM METRIC_GAUGE;");
        template.execute("DELETE FROM METRIC_TIMER;");
        template.execute("DELETE FROM METRIC_METER;");
        template.execute("DELETE FROM METRIC_HISTOGRAM;");
        template.execute("DELETE FROM METRIC_COUNTER;");
        return null;
    });
}