【问题标题】:JMH - Benchmarking SQL Queries In JavaJMH - 在 Java 中对 SQL 查询进行基准测试
【发布时间】:2022-09-23 16:15:29
【问题描述】:

我正在检查原始查询 PreparedStatement 之间的一些 sql 查询性能变化。由于我是使用 JMH 的初学者,因此无法了解内部流程如何调用我们的方法。在下面的代码中感到困惑:-

private static final String url = \"jdbc:postgresql://localhost:5432/postgres\";
static Connection getConnection(){
    try {
        conn = DriverManager.getConnection(url, user, password);
        System.out.println(\"Connected to the PostgresSQL server successfully. \");
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    }
    return conn;
}

@Benchmark
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@BenchmarkMode(Mode.SingleShotTime)
@Fork(value = 1, warmups = 5)
public static String executeSql() {
    if(conn == null) {
        conn = getConnection();
    }
    String query = \"select * from EmpDetails where EMP_ID=123 \";
    try (Statement stmt = conn.createStatement()) {
        ResultSet rs = stmt.executeQuery(query);
        while (rs.next()) {
            return rs.getString(1);
        }
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    }
    return \"\";
}

结果 :-

基准模式:单次调用时间
基准测试:com.mnk.BenchMarking.executeSql
运行进度:0.00% 完成,ETA 00:00:00
热身前叉:5 个中的 1 个
迭代 1:成功连接到 PostgresQL 服务器。
190.550 毫秒/操作

运行进度:完成 10.00%,ETA 00:00:11 热身叉:2 of 5 迭代 1:成功连接到 PostgresSQL 服务器。
174.217 毫秒/操作

运行进度:完成 20.00%,ETA 00:00:09 热身前叉:3 of 5 迭代 1:成功连接到 PostgresSQL 服务器。
175.219 毫秒/操作

运行进度:完成 30.00%,预计到达时间 00:00:08 热身叉:4 of 5 迭代 1:成功连接到 PostgresSQL 服务器。
180.964 毫秒/操作

运行进度:完成 40.00%,ETA 00:00:07 热身前叉:5 之 5 迭代 1:成功连接到 PostgresSQL 服务器。
163.894 毫秒/操作

在这里,我期望 getConnection() 方法只调用一次,并且每次迭代都会重用该连接对象。但是每次迭代都会调用 getConnection() 方法,这会导致无效结果。同样由于这个原因,我无法评估 executeQuery() 性能。

请有人提供有关我如何解决此问题的见解。

    标签: java postgresql benchmarking jmh


    【解决方案1】:

    在 JMH 中,您应该将所有初始化例程保存在使用 @Setup 注释的方法中,请参阅 JMH 示例中的示例:https://github.com/openjdk/jmh/blob/master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_05_StateFixtures.java

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-17
      相关资源
      最近更新 更多