-1

I'm trying to compare the performance of 2 queries by getting a connection, prepare the statement and execute query. Capturing the time taken using System.currentTimeMillis() before and after executeQuery().

Ironically whatever may be the query, time taken is always the same.(Ignoring the first execution)

Can someone please let me know, how to get the correct time taken by the query to execute ?

Code snippet:

Connection conn = DriverManager.getConnection(url,"721junits","721junits");
Statement stmt = conn.createStatement();
ResultSet rs;
long startTime = System.currentTimeMillis();
rs = stmt.executeQuery(sql);
long endTime = System.currentTimeMillis();
conn.close();

System.out.println("Total time taken : "+ (endTime - startTime));
  • Why are you assuming the number you get is wrong? But, to be sure, you should also consume the returned `ResultSet`. Depending on the JDBC driver, it may have deferred the actual execution, though it is unlikely. – Andreas Mar 21 '16 at 18:22
  • Maybe your two queries take the same time because the SQL execution plan is the same? If both cause a full table scan, you'd expect them to take the same amount of time to run. – Andreas Mar 21 '16 at 18:24

1 Answers1

0

you should use system.nanoTime()

Connection conn = DriverManager.getConnection(url,"721junits","721junits");
Statement stmt = conn.createStatement();
ResultSet rs;
long startTime = System.nanoTime();
rs = stmt.executeQuery(sql);
long endTime = System.nanoTime();
conn.close();

System.out.println("Total time taken : "+ (endTime - startTime));

read this answer for more info

Community
  • 1
  • 1
SpringLearner
  • 13,738
  • 20
  • 78
  • 116