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:de.unisb.cs.st.javaslicer.jung.ShowJungGraph.java

public static void main(String[] args) throws InterruptedException {
    Options options = createOptions();/* ww w  .  j  av a 2  s  .  c o m*/
    CommandLineParser parser = new GnuParser();
    CommandLine cmdLine;

    try {
        cmdLine = parser.parse(options, args, true);
    } catch (ParseException e) {
        System.err.println("Error parsing the command line arguments: " + e.getMessage());
        return;
    }

    if (cmdLine.hasOption('h')) {
        printHelp(options, System.out);
        System.exit(0);
    }

    String[] additionalArgs = cmdLine.getArgs();
    if (additionalArgs.length != 2) {
        printHelp(options, System.err);
        System.exit(-1);
    }
    File traceFile = new File(additionalArgs[0]);
    String slicingCriterionString = additionalArgs[1];

    Long threadId = null;
    if (cmdLine.hasOption('t')) {
        try {
            threadId = Long.parseLong(cmdLine.getOptionValue('t'));
        } catch (NumberFormatException e) {
            System.err.println("Illegal thread id: " + cmdLine.getOptionValue('t'));
            System.exit(-1);
        }
    }

    TraceResult trace;
    try {
        trace = TraceResult.readFrom(traceFile);
    } catch (IOException e) {
        System.err.format("Could not read the trace file \"%s\": %s%n", traceFile, e);
        System.exit(-1);
        return;
    }

    List<SlicingCriterion> sc = null;
    try {
        sc = StaticSlicingCriterion.parseAll(slicingCriterionString, trace.getReadClasses());
    } catch (IllegalArgumentException e) {
        System.err.println("Error parsing slicing criterion: " + e.getMessage());
        System.exit(-1);
        return;
    }

    List<ThreadId> threads = trace.getThreads();
    if (threads.size() == 0) {
        System.err.println("The trace file contains no tracing information.");
        System.exit(-1);
    }

    ThreadId tracing = null;
    for (ThreadId t : threads) {
        if (threadId == null) {
            if ("main".equals(t.getThreadName())
                    && (tracing == null || t.getJavaThreadId() < tracing.getJavaThreadId()))
                tracing = t;
        } else if (t.getJavaThreadId() == threadId.longValue()) {
            tracing = t;
        }
    }

    if (tracing == null) {
        System.err.println(threadId == null ? "Couldn't find the main thread."
                : "The thread you specified was not found.");
        System.exit(-1);
        return;
    }

    Transformer<InstructionInstance, Object> transformer;
    Transformer<Object, String> vertexLabelTransformer;
    Transformer<Object, String> vertexTooltipTransformer;

    String granularity = cmdLine.getOptionValue("granularity");
    if (granularity == null || "instance".equals(granularity)) {
        transformer = new Transformer<InstructionInstance, Object>() {
            @Override
            public InstructionInstance transform(InstructionInstance inst) {
                return inst;
            }
        };
        vertexLabelTransformer = new Transformer<Object, String>() {
            @Override
            public String transform(Object inst) {
                return getShortInstructionText(((InstructionInstance) inst).getInstruction());
            }
        };
        vertexTooltipTransformer = new Transformer<Object, String>() {
            @Override
            public String transform(Object inst) {
                return getInstructionTooltip(((InstructionInstance) inst).getInstruction());
            }
        };
    } else if ("instruction".equals(granularity)) {
        transformer = new Transformer<InstructionInstance, Object>() {
            @Override
            public Instruction transform(InstructionInstance inst) {
                return inst.getInstruction();
            }
        };
        vertexLabelTransformer = new Transformer<Object, String>() {
            @Override
            public String transform(Object inst) {
                return getShortInstructionText(((Instruction) inst));
            }
        };
        vertexTooltipTransformer = new Transformer<Object, String>() {
            @Override
            public String transform(Object inst) {
                return getInstructionTooltip(((Instruction) inst));
            }
        };
    } else if ("line".equals(granularity)) {
        transformer = new Transformer<InstructionInstance, Object>() {
            @Override
            public Line transform(InstructionInstance inst) {
                return new Line(inst.getInstruction().getMethod(), inst.getInstruction().getLineNumber());
            }
        };
        vertexLabelTransformer = new Transformer<Object, String>() {
            @Override
            public String transform(Object inst) {
                Line line = (Line) inst;
                return line.getMethod().getName() + ":" + line.getLineNr();
            }
        };
        vertexTooltipTransformer = new Transformer<Object, String>() {
            @Override
            public String transform(Object inst) {
                Line line = (Line) inst;
                return "Line " + line.getLineNr() + " in method " + line.getMethod().getReadClass().getName()
                        + "." + line.getMethod();
            }
        };
    } else {
        System.err.println("Illegal granularity specification: " + granularity);
        System.exit(-1);
        return;
    }

    int maxLevel = Integer.MAX_VALUE;
    if (cmdLine.hasOption("maxlevel")) {
        try {
            maxLevel = Integer.parseInt(cmdLine.getOptionValue("maxlevel"));
        } catch (NumberFormatException e) {
            System.err.println("Argument to \"maxlevel\" must be an integer.");
            System.exit(-1);
            return;
        }
    }

    long startTime = System.nanoTime();
    ShowJungGraph<Object> showGraph = new ShowJungGraph<Object>(trace, transformer);
    showGraph.setMaxLevel(maxLevel);
    showGraph.setVertexLabelTransformer(vertexLabelTransformer);
    showGraph.setVertexTooltipTransformer(vertexTooltipTransformer);
    if (cmdLine.hasOption("progress"))
        showGraph.addProgressMonitor(new ConsoleProgressMonitor());
    boolean multithreaded;
    if (cmdLine.hasOption("multithreaded")) {
        String multithreadedStr = cmdLine.getOptionValue("multithreaded");
        multithreaded = ("1".equals(multithreadedStr) || "true".equals(multithreadedStr));
    } else {
        multithreaded = Runtime.getRuntime().availableProcessors() > 1;
    }

    DirectedGraph<Object, SliceEdge<Object>> graph = showGraph.getGraph(tracing, sc, multithreaded);
    long endTime = System.nanoTime();

    System.out.format((Locale) null, "%nSlice graph consists of %d nodes.%n", graph.getVertexCount());
    System.out.format((Locale) null, "Computation took %.2f seconds.%n", 1e-9 * (endTime - startTime));

    showGraph.displayGraph(graph);
}

From source file:StopWatch.java

public long nanoEllapsed() {
    return System.nanoTime() - n0;
}

From source file:nars.util.meter.event.PeriodMeter.java

public static double now(boolean nanoSeconds /* TODO use a Resolution enum */) {
    return nanoSeconds ? System.nanoTime() : System.currentTimeMillis() * 1.0E6;
}

From source file:com.genericworkflownodes.knime.custom.ZipUtilsTest.java

public static File createTempDirectory() throws IOException {
    final File temp;

    temp = File.createTempFile("temp", Long.toString(System.nanoTime()));

    if (!(temp.delete())) {
        throw new IOException("Could not delete temp file: " + temp.getAbsolutePath());
    }//from w ww. j  a  v a2  s. c o  m

    if (!(temp.mkdir())) {
        throw new IOException("Could not create temp directory: " + temp.getAbsolutePath());
    }

    return (temp);
}

From source file:Main.java

public static void sleep(long timeout, int nanos) {
    //the Thread.sleep method is not precise at all regarding nanos
    if (timeout > 0 || nanos > 900000) {
        try {/*from w  w w. j a v  a 2s.c o  m*/
            Thread.sleep(timeout + (nanos / 1000000), (nanos % 1000000));
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    } else {
        //this isn't a superb metronome either, but allows a granularity
        //with a reasonable precision in the order of 50ths of millisecond
        long initialTime = System.nanoTime() - 200;
        while (System.nanoTime() < initialTime + nanos)
            ;
    }
}

From source file:com.arkatay.yada.base.Time.java

/**
 * Initializes the time system//from  ww  w  .  j  av  a  2s . c o  m
 *
 */
public static void init() {
    // Create a logger for this class
    Log log = LogFactory.getLog(Time.class);

    // try the nanoTime method
    useNanoTimeMethod = true;
    try {
        System.nanoTime();
    } catch (NoSuchMethodError err) {
        initTimeMillis = System.currentTimeMillis();
        useNanoTimeMethod = false;
        log.warn("!!!");
        log.warn("!!! The java runtime does not support the System.nanoTime method and this means that the");
        log.warn("!!! timer accuracy on some computer may be too low for the codec to function properly!");
        log.warn("!!! Consider using JRE 1.5.x or higher which supports the nanoTime method");
        log.warn("!!!");
    }
}

From source file:com.daphne.es.common.test.BaseUserIT.java

public User createUser() {
    User user = new User();
    user.setUsername("zhangkaitao$$$" + System.nanoTime() + RandomStringUtils.random(10));
    user.setPassword("123456");
    user.setRegisterDate(new Date());
    BaseInfo baseInfo = new BaseInfo();
    baseInfo.setRealname("zhangkaitao");
    baseInfo.setSex(Sex.male);//  ww w . j  a v a  2s .com
    baseInfo.setBirthday(new Timestamp(System.currentTimeMillis()));
    baseInfo.setAge(15);
    user.setBaseInfo(baseInfo);

    SchoolInfo primary = new SchoolInfo();
    primary.setName("abc");
    primary.setType(SchoolType.primary_school);
    user.addSchoolInfo(primary);

    SchoolInfo secondary = new SchoolInfo();
    secondary.setName("bcd");
    secondary.setType(SchoolType.secondary_school);
    user.addSchoolInfo(secondary);

    SchoolInfo high = new SchoolInfo();
    high.setName("cde");
    high.setType(SchoolType.high_school);
    user.addSchoolInfo(high);

    SchoolInfo university = new SchoolInfo();
    university.setName("def");
    university.setType(SchoolType.university);
    user.addSchoolInfo(university);

    return user;
}

From source file:Main.java

/**
 * Causes the current Thread to sleep for the specified number of milliseconds.  If the current Thread is interrupted
 * during sleep, the interrupt flag on the current Thread will remain set and the duration, in milliseconds, of completed sleep is returned.
 * <p/>/*w  w  w  . ja  v a  2s .  com*/
 * @param milliseconds an integer value specifying the number of milliseconds the current Thread should sleep.
 * @return a long value indicating duration in milliseconds of completed sleep by the current Thread.
 * @see java.lang.System#nanoTime()
 * @see java.lang.Thread#sleep(long)
 */
public static long sleep(final long milliseconds) {
    final long t0 = System.nanoTime();

    try {
        Thread.sleep(milliseconds);
    } catch (InterruptedException ignore) {
        Thread.currentThread().interrupt();
    }

    return (System.nanoTime() - t0) / 1000;
}

From source file:com.dangdang.ddframe.test.EmbedZookeeperTestExecutionListener.java

private static void startEmbedTestingServer() {
    if (null != testingServer) {
        return;/*from   ww  w . j a  v a 2 s.  co m*/
    }
    try {
        testingServer = new TestingServer(3181,
                new File(String.format("target/test_zk_data/%s/", System.nanoTime())));
        // CHECKSTYLE:OFF
    } catch (final Exception ex) {
        // CHECKSTYLE:ON
        RegExceptionHandler.handleException(ex);
    } finally {
        Runtime.getRuntime().addShutdownHook(new Thread() {

            @Override
            public void run() {
                try {
                    BlockUtils.sleep(2000L);
                    testingServer.close();
                } catch (final IOException ex) {
                    RegExceptionHandler.handleException(ex);
                }
            }
        });
    }
}

From source file:com.relicum.ipsum.Utils.Profiler.java

public static long getCurrentDelta(String id) {
    final long nanos = System.nanoTime();
    Validate.notNull(id, "ID should not be null");
    synchronized (startTimes) {
        if (!startTimes.containsKey(id)) {
            throw new IllegalStateException("This ID is not being profiled!");
        }//from   w  w w . j  av a 2  s .  co  m
        return nanos - startTimes.get(id);
    }
}