Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The one flaw in that approach is that the "real" time <code>doSomething()</code> takes to execute can vary wildly depending on what other programs are running on the system and what its load is. This makes the performance measurement somewhat imprecise.</p> <p>One more accurate way of tracking the time it takes to execute code, assuming the code is single-threaded, is to look at the CPU time consumed by the thread during the call. You can do this with the JMX classes; in particular, with <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/management/ThreadMXBean.html" rel="nofollow noreferrer"><code>ThreadMXBean</code></a>. You can retrieve an instance of <code>ThreadMXBean</code> from <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/management/ManagementFactory.html" rel="nofollow noreferrer"><code>java.lang.management.ManagementFactory</code></a>, and, if your platform supports it (most do), use the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/management/ThreadMXBean.html#getCurrentThreadCpuTime()" rel="nofollow noreferrer"><code>getCurrentThreadCpuTime</code></a> method in place of <code>System.currentTimeMillis</code> to do a similar test. Bear in mind that <code>getCurrentThreadCpuTime</code> reports time in nanoseconds, not milliseconds.</p> <p>Here's a sample (Scala) method that could be used to perform a measurement:</p> <pre><code>def measureCpuTime(f: =&gt; Unit): java.time.Duration = { import java.lang.management.ManagementFactory.getThreadMXBean if (!getThreadMXBean.isThreadCpuTimeSupported) throw new UnsupportedOperationException( "JVM does not support measuring thread CPU-time") var finalCpuTime: Option[Long] = None val thread = new Thread { override def run(): Unit = { f finalCpuTime = Some(getThreadMXBean.getThreadCpuTime( Thread.currentThread.getId)) } } thread.start() while (finalCpuTime.isEmpty &amp;&amp; thread.isAlive) { Thread.sleep(100) } java.time.Duration.ofNanos(finalCpuTime.getOrElse { throw new Exception("Operation never returned, and the thread is dead " + "(perhaps an unhandled exception occurred)") }) } </code></pre> <p>(Feel free to translate the above to Java!)</p> <p>This strategy isn't perfect, but it's less subject to variations in system load.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload