Java性能测试 [英] Java Performance Testing

查看:117
本文介绍了Java性能测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Java应用程序上进行一些计时测试。这就是我目前正在做的事情:

I want to do some timing tests on a Java application. This is what I am currently doing:

long startTime = System.currentTimeMillis();
doSomething();
long finishTime = System.currentTimeMillis();
System.out.println("That took: " + (finishTime - startTime) + " ms");

这样的性能测试是否有错误?什么是更好的方式?

Is there anything "wrong" with performance testing like this? What is a better way?

重复秒表基准可以接受吗?

推荐答案

这种方法的一个缺陷是真正的时间 doSomething()执行可能会有很大的不同,具体取决于系统上运行的其他程序及其负载。这使得性能测量有些不精确。

The one flaw in that approach is that the "real" time doSomething() 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.

一种更准确的方法来跟踪执行代码所花费的时间,假设代码是单线程的,就是看一下调用期间线程消耗的CPU时间。您可以使用JMX类执行此操作;特别是 ThreadMXBean的 。您可以从 ThreadMXBean 的实例management / ManagementFactory.htmlrel =nofollow noreferrer> java.lang.management.ManagementFactory ,如果您的平台支持它(大部分都支持),使用 getCurrentThreadCpuTime 方法代替 System.currentTimeMillis 进行类似的测试。请记住 getCurrentThreadCpuTime 报告的时间以纳秒为单位,而不是毫秒。

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 ThreadMXBean. You can retrieve an instance of ThreadMXBean from java.lang.management.ManagementFactory, and, if your platform supports it (most do), use the getCurrentThreadCpuTime method in place of System.currentTimeMillis to do a similar test. Bear in mind that getCurrentThreadCpuTime reports time in nanoseconds, not milliseconds.

这是一个示例(Scala)方法,可以用于执行度量:

Here's a sample (Scala) method that could be used to perform a measurement:

def measureCpuTime(f: => 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 && 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)")
  })
}

(随意将上述内容翻译成Java!)

(Feel free to translate the above to Java!)

此策略并不完美,但它不受系统负载变化的影响。

This strategy isn't perfect, but it's less subject to variations in system load.

这篇关于Java性能测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆