Example usage for java.time Duration ofNanos

List of usage examples for java.time Duration ofNanos

Introduction

In this page you can find the example usage for java.time Duration ofNanos.

Prototype

public static Duration ofNanos(long nanos) 

Source Link

Document

Obtains a Duration representing a number of nanoseconds.

Usage

From source file:Main.java

public static void main(String[] args) {
    Duration duration = Duration.ofNanos(10);
    System.out.println(duration);
}

From source file:Main.java

public static void main(String[] args) {
    Duration duration = Duration.ofDays(33); //seconds or nanos

    Duration duration1 = Duration.ofHours(33); //seconds or nanos
    Duration duration2 = Duration.ofMillis(33); //seconds or nanos
    Duration duration3 = Duration.ofMinutes(33); //seconds or nanos
    Duration duration4 = Duration.ofNanos(33); //seconds or nanos
    Duration duration5 = Duration.ofSeconds(33); //seconds or nanos
    Duration duration6 = Duration.between(LocalDate.of(2012, 11, 11), LocalDate.of(2013, 1, 1));

    System.out.println(duration6.getSeconds());
    System.out.println(duration.getNano());
    System.out.println(duration.getSeconds());
}

From source file:com.joyent.manta.client.multipart.JobsMultipartManagerIT.java

public void willRunFunctionWhenWaitingTooLong() throws IOException {
    String[] parts = new String[] { "Hello ", "world ", "Joyent", "!" };

    final String name = uploadName("will-run-function-when-waiting-too-long");
    final String path = testPathPrefix + name;

    final JobsMultipartUpload upload = multipart.initiateUpload(path);
    final ArrayList<MantaMultipartUploadTuple> uploadedParts = new ArrayList<>();

    for (int i = 0; i < parts.length; i++) {
        String part = parts[i];/*from  w w  w .  j a v  a  2s  .  c om*/
        int partNumber = i + 1;
        MantaMultipartUploadTuple uploaded = multipart.uploadPart(upload, partNumber, part);
        uploadedParts.add(uploaded);
    }

    multipart.validateThatThereAreSequentialPartNumbers(upload);
    multipart.complete(upload, uploadedParts);

    Boolean flagChanged = multipart.waitForCompletion(upload, Duration.ofNanos(0L), 1, uuid -> true);

    assertTrue(flagChanged, "wait timeout exceeded function was never run");
}

From source file:com.joyent.manta.client.multipart.EncryptedJobsMultipartManagerIT.java

public void willRunFunctionWhenWaitingTooLong() throws IOException {
    String[] parts = new String[] { "Hello ", "world ", "Joyent", "!" };

    final String name = uploadName("will-run-function-when-waiting-too-long");
    final String path = testPathPrefix + name;

    final EncryptedMultipartUpload<JobsMultipartUpload> upload = multipart.initiateUpload(path);
    final ArrayList<MantaMultipartUploadTuple> uploadedParts = new ArrayList<>();

    for (int i = 0; i < parts.length; i++) {
        String part = parts[i];//from   w  ww .  j  a  va  2  s.  c  o m
        int partNumber = i + 1;
        MantaMultipartUploadTuple uploaded = multipart.uploadPart(upload, partNumber, part);
        uploadedParts.add(uploaded);
    }

    multipart.validateThatThereAreSequentialPartNumbers(upload);
    multipart.complete(upload, uploadedParts);

    Boolean flagChanged = multipart.getWrapped().waitForCompletion(upload, Duration.ofNanos(0L), 1,
            uuid -> true);

    assertTrue(flagChanged, "wait timeout exceeded function was never run");
}

From source file:com.joyent.manta.benchmark.Benchmark.java

/**
 * Method used to run a simple single-threaded benchmark.
 *
 * @param method to measure//from w w w .  ja va  2  s.  co  m
 * @param path path to store benchmarking test data
 * @param iterations number of iterations to run
 * @throws IOException thrown when we can't communicate with the server
 */
private static void singleThreadedBenchmark(final String method, final String path, final int iterations)
        throws IOException {
    Runtime.getRuntime().addShutdownHook(new Thread(Benchmark::cleanUp));

    long fullAggregation = 0;
    long serverAggregation = 0;

    final long testStart = System.nanoTime();

    for (int i = 0; i < iterations; i++) {
        Duration[] durations;

        if (method.equals("put")) {
            durations = measurePut(sizeInBytesOrNoOfDirs);
        } else if (method.equals("putDir")) {
            durations = measurePutDir(sizeInBytesOrNoOfDirs);
        } else {
            durations = measureGet(path);
        }

        long fullLatency = durations[0].toMillis();
        long serverLatency = durations[1].toMillis();
        fullAggregation += fullLatency;
        serverAggregation += serverLatency;

        System.out.printf("%s %d full=%dms, server=%dms\n", method, i, fullLatency, serverLatency);
    }

    final long testEnd = System.nanoTime();

    final long fullAverage = Math.round(fullAggregation / iterations);
    final long serverAverage = Math.round(serverAggregation / iterations);
    final long totalTime = testEnd - testStart;

    System.out.printf("Average full latency: %d ms\n", fullAverage);
    System.out.printf("Average server latency: %d ms\n", serverAverage);
    System.out.printf("Total test time: %d ms\n", Duration.ofNanos(totalTime).toMillis());
}

From source file:com.joyent.manta.benchmark.Benchmark.java

/**
 * Method used to run a multi-threaded benchmark.
 *
 * @param method to measure//from  w w w  .  ja  v a2 s  . c  o m
 * @param path path to store benchmarking test data
 * @param iterations number of iterations to run
 * @param concurrency number of threads to run
 * @throws IOException thrown when we can't communicate with the server
 */
private static void multithreadedBenchmark(final String method, final String path, final int iterations,
        final int concurrency) throws IOException {
    final AtomicLong fullAggregation = new AtomicLong(0L);
    final AtomicLong serverAggregation = new AtomicLong(0L);
    final AtomicLong count = new AtomicLong(0L);
    final long perThreadCount = perThreadCount(iterations, concurrency);

    System.out.printf("Running %d iterations per thread\n", perThreadCount);

    final long testStart = System.nanoTime();

    Runtime.getRuntime().addShutdownHook(new Thread(Benchmark::cleanUp));

    final Callable<Void> worker = () -> {
        for (int i = 0; i < perThreadCount; i++) {
            Duration[] durations;

            if (method.equals("put")) {
                durations = measurePut(sizeInBytesOrNoOfDirs);
            } else if (method.equals("putDir")) {
                durations = measurePutDir(sizeInBytesOrNoOfDirs);
            } else {
                durations = measureGet(path);
            }

            long fullLatency = durations[0].toMillis();
            long serverLatency = durations[1].toMillis();
            fullAggregation.addAndGet(fullLatency);
            serverAggregation.addAndGet(serverLatency);

            System.out.printf("%s %d full=%dms, server=%dms, thread=%s\n", method, count.getAndIncrement(),
                    fullLatency, serverLatency, Thread.currentThread().getName());
        }

        return null;
    };

    final Thread.UncaughtExceptionHandler handler = (t, e) -> LOG.error("Error when executing benchmark", e);

    final AtomicInteger threadCounter = new AtomicInteger(0);
    ThreadFactory threadFactory = r -> {
        Thread t = new Thread(r);
        t.setDaemon(true);
        t.setUncaughtExceptionHandler(handler);
        t.setName(String.format("benchmark-%d", threadCounter.incrementAndGet()));

        return t;
    };

    ExecutorService executor = Executors.newFixedThreadPool(concurrency, threadFactory);

    List<Callable<Void>> workers = new ArrayList<>(concurrency);
    for (int i = 0; i < concurrency; i++) {
        workers.add(worker);
    }

    try {
        List<Future<Void>> futures = executor.invokeAll(workers);

        boolean completed = false;
        while (!completed) {
            try (Stream<Future<Void>> stream = futures.stream()) {
                completed = stream.allMatch((f) -> f.isDone() || f.isCancelled());

                if (!completed) {
                    Thread.sleep(CHECK_INTERVAL);
                }
            }
        }

    } catch (InterruptedException e) {
        return;
    } finally {
        System.err.println("Shutting down the thread pool");
        executor.shutdown();
    }

    final long testEnd = System.nanoTime();

    final long fullAverage = Math.round(fullAggregation.get() / iterations);
    final long serverAverage = Math.round(serverAggregation.get() / iterations);
    final long totalTime = Duration.ofNanos(testEnd - testStart).toMillis();

    System.out.printf("Average full latency: %d ms\n", fullAverage);
    System.out.printf("Average server latency: %d ms\n", serverAverage);
    System.out.printf("Total test time: %d ms\n", totalTime);
    System.out.printf("Total invocations: %d\n", count.get());
}

From source file:com.joyent.manta.client.MantaClientFindIT.java

/**
 * This test sees if find() can find a large number of files spread across
 * many directories. It validates the results against the node.js Manta CLI
 * tool mls./*from   w ww.j  a  v  a  2  s. co  m*/
 *
 * This test is disabled by default because it is difficult to know if the
 * running system has the node.js CLI tools properly installed. Please run
 * this test manually on an as-needed basis.
 */
@Test(enabled = false)
public void findMatchesMfind() throws SecurityException, IOException, InterruptedException {
    ConfigContext context = mantaClient.getContext();
    String reports = context.getMantaHomeDirectory() + SEPARATOR + "reports" + SEPARATOR + "usage" + SEPARATOR
            + "summary";
    String[] cmd = new String[] { "mfind", reports };

    ProcessBuilder processBuilder = new ProcessBuilder(cmd);

    Map<String, String> env = processBuilder.environment();
    env.put("MANTA_URL", context.getMantaURL());
    env.put("MANTA_USER", context.getMantaUser());
    env.put("MANTA_KEY_ID", context.getMantaKeyId());

    long mFindStart = System.nanoTime();
    Process process = processBuilder.start();

    String charsetName = StandardCharsets.UTF_8.name();

    List<String> objects = new LinkedList<>();

    try (Scanner scanner = new Scanner(process.getInputStream(), charsetName)) {
        while (scanner.hasNextLine()) {
            objects.add(scanner.nextLine());
        }
    }

    System.err.println("Waiting for mfind to complete");
    Assert.assertEquals(process.waitFor(), 0, "mfind exited with an error");
    long mFindEnd = System.nanoTime();
    System.err.printf("mfind process completed in %d ms\n", Duration.ofNanos(mFindEnd - mFindStart).toMillis());

    long findStart = System.nanoTime();

    List<String> foundObjects;
    try (Stream<MantaObject> findStream = mantaClient.find(reports)) {
        foundObjects = findStream.map(MantaObject::getPath).collect(Collectors.toList());
    }

    long findEnd = System.nanoTime();
    System.err.printf("find() completed in %d ms\n", Duration.ofNanos(findEnd - findStart).toMillis());

    Assert.assertEqualsNoOrder(objects.toArray(), foundObjects.toArray());
}

From source file:com.joyent.manta.benchmark.Benchmark.java

/**
 * Measures the total time to put an object to Manta.
 *
 * @param length number of bytes to write
 * @return two durations - full time in the JVM, server time processing
 * @throws IOException thrown when we can't access Manta over the network
 *//*ww  w. j  ava  2s .co m*/
private static Duration[] measurePut(final long length) throws IOException {
    final String path = String.format("%s/%s", testDirectory, UUID.randomUUID());
    final long start = System.nanoTime();
    final String serverLatencyString;

    try (RandomInputStream rand = new RandomInputStream(length)) {
        MantaHttpHeaders headers = new MantaHttpHeaders();
        headers.setDurabilityLevel(2);

        serverLatencyString = client.put(path, rand, length, headers, null).getHeader("x-response-time")
                .toString();
    }

    final long stop = System.nanoTime();

    Duration serverLatency = Duration.ofMillis(Long.parseLong(serverLatencyString));
    Duration fullLatency = Duration.ofNanos(stop - start);
    return new Duration[] { fullLatency, serverLatency };
}

From source file:com.joyent.manta.benchmark.Benchmark.java

/**
 * Measures the total time to put multiple directories to Manta.
 *
 * @param diretoryCount number of directories to create
 * @return two durations - full time in the JVM, -1 because server time is unavailable
 * @throws IOException thrown when we can't access Manta over the network
 *//*from w w  w . j  a va  2 s. c  o m*/
private static Duration[] measurePutDir(final int diretoryCount) throws IOException {
    final StringBuilder path = new StringBuilder().append(testDirectory);

    for (int i = 0; i < diretoryCount; i++) {
        path.append(MantaClient.SEPARATOR).append(STRING_GENERATOR.generate(2));
    }

    final long start = System.nanoTime();

    client.putDirectory(path.toString(), true);

    final long stop = System.nanoTime();

    Duration serverLatency = Duration.ofMillis(-1L);
    Duration fullLatency = Duration.ofNanos(stop - start);
    return new Duration[] { fullLatency, serverLatency };
}