繁体   English   中英

使用System.CurrentTimeMillis()测量时间的Java错误

[英]Java error measuring time with System.CurrentTimeMillis()

我目前在测量SQL查询在JAVA代码中花费的时间时遇到问题。 在下面的代码中, stmt.executeQuery(query.getQuery()); 将执行一个SQL查询,我正在使用System.currentTimeMillis()来查看查询需要多长时间。 问题是,在下面的jsp页面中,我在其中查看queryTime的结果,得到的结果例如The query took 18:00:00:055 time. 用于一个非常简单的数据库(2个非常小的表)和一个非常简单的查询。 18小时显然不是一个现实的时间,因为查询在我的计算机上运行仅需几毫秒。 我究竟做错了什么?

编辑:作为对提交的答案的响应,我正在将queryDuration与提交用于测试和获取结果的sql查询一起输出到控制台,例如(其中输入毫秒的毫秒数是在输入SQL查询之后输出的):

query (from controller): select * from service_request
milliseconds: 1
query (from controller): select * from data_file where service_request_id =     '2'
milliseconds: 0
path: www.foobar.com/custom/bin/lib/
path: www.foobar.com/images/resources/
query (from controller): select FN_Contact from service_request where Notes   IS NOT NULL
milliseconds: 10
query (from controller): select FN_Contact from service_request where Notes IS NULL
milliseconds: 0
query (from controller): select Notes, LN_Contact from service_request where   FN_Contact = 'Amanda'
milliseconds: 0 

当一些看似更复杂的查询在更少的时间内完成时,这有什么意义呢? (这些表很小,每个表中有4-5列,每个表中有4-5条目)

java计算查询时间:

long queryStart = System.currentTimeMillis();
ResultSet rs = stmt.executeQuery(query.getQuery());
long queryEnd = System.currentTimeMillis();
long queryDuration = queryEnd-queryStart;
Date queryDurationTime = new Date(queryDuration);
DateFormat formatter = new SimpleDateFormat("HH:mm:ss:SSS");
String dateFormatted = formatter.format(queryDurationTime);
queryTime = dateFormatted;

在jsp页面上显示queryTime:

<c:choose>
    <c:when test="${empty queryTime}">
    </c:when>
    <c:otherwise>
        <h3>Results:</h3>
        The query took ${queryTime} time.
    </c:otherwise>
</c:choose>

您可以简单地做到这一点,而无需进行时间转换。

使用Thread.sleep()模拟1000毫秒操作的示例;

public static void main(String[] args) throws InterruptedException {
        long queryStart = System.currentTimeMillis();
        Thread.sleep(1000);
        long queryEnd = System.currentTimeMillis();
        long queryDuration = queryEnd - queryStart;
        // Date queryDurationTime = new Date(queryDuration);
        // DateFormat formatter = new SimpleDateFormat("HH:mm:ss:SSS");
        // String dateFormatted = formatter.format(queryDurationTime);
        // queryTime = dateFormatted;
        System.out.println(queryDuration);
    }

问题是您要将时差(以毫秒为单位)转换为日期。 返回以毫秒为单位的queryDuration ,或将queryStartqueryEnd包装在Date对象中,然后减去两个日期。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM