0

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.

Bacara
  • 6,903
  • 1
  • 20
  • 21
  • 2
    It's not a trivial subject. The following is a good starting point for Java: http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java – NPE Feb 04 '17 at 11:01
  • The time it takes to do anything in Java varies based on many factors. The same function might appear to take 50 ms or no time at all depending on what it does and how you run it. – Peter Lawrey Feb 04 '17 at 11:46

1 Answers1

2

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!
Freeman
  • 9,464
  • 7
  • 35
  • 58