Search code examples
javapythoncpucycle

calculate CPU Cycle for Java function


I'd like to know how to calculate the CPU Cycle for a function in Java or Python.

I tried out in Java with:

(OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); osbean.getProcessCpuTime();

But no results.


Solution

  • in Python,

    use timeit.default_timer(); it uses the most accurate option for your platform. in Ubuntu, this will use time.time() instead.

    timeit.default_timer()Define a default timer, in a platform-specific manner. On Windows, time.clock() has microsecond granularity, but time.time()‘s granularity is 1/60th of a second. On Unix, time.clock() has 1/100th of a second granularity, and time.time() is much more precise. On either platform, default_timer() measures wall clock time, not the CPU time. This means that other processes running on the same computer may interfere with the timing.

    in JAVA,

    1. System.currentTimeMillis() will only ever measure wall-clock time, never CPU time.
    2. If you need wall-clock time, then System.nanoTime() is often more precise (and never worse) than currentTimeMillis().
    3. ThreadMXBean.getThreadCPUTime() can help you find out how much CPU time a given thread has used. Use ManagementFactory.getThreadMXBean() to get a ThreadMXBean and Thread.getId() to find the id of the thread you're interested in. Note that this method need not be supported on every JVM!