面试题答案
一键面试- 测量响应时间:
- 使用System.currentTimeMillis():
- 记录方法调用前的时间戳。
- 调用目标方法。
- 记录方法调用后的时间戳。
- 计算时间差,即响应时间。
- 示例代码如下:
- 使用System.currentTimeMillis():
public class PerformanceTest {
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int num1 = 5;
int num2 = 3;
long startTime = System.currentTimeMillis();
int result = add(num1, num2);
long endTime = System.currentTimeMillis();
long responseTime = endTime - startTime;
System.out.println("响应时间:" + responseTime + " 毫秒");
}
}
- 使用System.nanoTime():
- System.nanoTime()提供更高精度的时间测量,适合测量非常短的时间间隔。
- 同样在方法调用前后记录时间戳,计算差值。
- 示例代码如下:
public class PerformanceTest {
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int num1 = 5;
int num2 = 3;
long startTime = System.nanoTime();
int result = add(num1, num2);
long endTime = System.nanoTime();
long responseTime = endTime - startTime;
System.out.println("响应时间:" + responseTime + " 纳秒");
}
}
- 测量吞吐量:
- 定义测试次数:选择一个合适的测试次数
n
,多次调用目标方法。 - 记录总时间:使用
System.currentTimeMillis()
或System.nanoTime()
记录这n
次调用的总时间。 - 计算吞吐量:吞吐量 = 调用次数 / 总时间。
- 示例代码如下:
- 定义测试次数:选择一个合适的测试次数
public class PerformanceTest {
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int num1 = 5;
int num2 = 3;
int testCount = 1000000;
long startTime = System.currentTimeMillis();
for (int i = 0; i < testCount; i++) {
add(num1, num2);
}
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
double throughput = (double) testCount / totalTime * 1000;
System.out.println("吞吐量:" + throughput + " 次/秒");
}
}
- 使用工具:
- JMH(Java Microbenchmark Harness):
- 引入JMH依赖。
- 创建一个基准测试类,使用
@Benchmark
注解标记目标方法。 - 运行基准测试,JMH会自动计算吞吐量等性能指标。
- 示例代码如下:
- JMH(Java Microbenchmark Harness):
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
@State(Scope.Thread)
public class AddBenchmark {
int num1 = 5;
int num2 = 3;
@Benchmark
public int add() {
return num1 + num2;
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(AddBenchmark.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
}
在上述JMH示例中,运行main
方法后,JMH会输出包括吞吐量等详细的性能测试结果。