【问题标题】:Measure response time in java (web service)?测量java(Web服务)中的响应时间?
【发布时间】:2015-05-05 22:35:47
【问题描述】:

我正在尝试测量“进程”的响应时间(我正在从服务器请求数据,然后呈现数据)。我想测量从我请求数据(当我按下“发送”按钮时)到数据显示在我的 txtbox 中所花费的时间。

看起来像这样:

    (these two are at the very top:)
    private long a
    private long b


   ...other code...


    a = System.currentTimeMillis();

    btnSend.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent arg0) {
            String fileContents;
            b = System.currentTimeMillis();
            try {
                fileContents = control.getFileContents(txtSearch.getText());
                txtView.setText(fileContents + "\n" + "\n" + "The process took "+(b-a)+"milliseconds to execute." + "\n" + "("+((b-a)/1000)+" seconds)");

            } catch (RemoteException e) {
                txtView.setText("File not found");
            }

        }

Ant 它可以工作,但只是第一次。如果我发送另一个请求,则时间只会添加到旧时间。第一个请求需要 2 秒,第二个请求需要 7 秒(实际上需要 2 秒)。

我尝试通过重置 a 和 b 来规避问题:

    a = 0; 
    b = 0;

在重置按钮中,但这似乎让事情变得有点疯狂。

关于如何解决问题的任何想法?

谢谢

【问题讨论】:

  • System.currentTimeMillis() 用于获取系统时间。要测量经过的时间,请使用 System.nanoTime()
  • @AntoineWils 如果使用纳米时间,我会以什么单位获得结果?
  • @cssprobs Erm,nanoseconds。您可以使用TimeUnit 将其转换为您想要的单位。
  • 数十亿秒。一旦你有经过的时间得到毫秒数,除以 100000。阅读这篇文章以了解其他方式stackoverflow.com/questions/924208/…
  • @AntoineWils 好的,我想我让它工作了,但我必须将纳秒除以 1 000 000 而不是 100 000,这似乎是正确的方法。

标签: java web-services soap response-time


【解决方案1】:

看起来很像您在创建按钮时设置 a 的值,而在单击它时设置 b 的值。如果您这样做,那么您将看到您所看到的结果。 A 将保持不变,B 将越来越远离它。然后当你重置时,事情会“有点疯狂”,因为现在 A 等于零。所以它会说你的往返花费了大约 45 年(自 1970 年以来的时间,即 currentTimeMillis() 的 0 值。)

相反,您希望在单击按钮时设置 A 的值,并在获得结果后设置 B。

像这样:

btnSend.addActionListener(new ActionListener(){

    @Override
    public void actionPerformed(ActionEvent arg0) {
        String fileContents;
        a = System.currentTimeMillis();
        try {
            fileContents = control.getFileContents(txtSearch.getText());
            b = System.currentTimeMillis();
            txtView.setText(fileContents + "\n" + "\n" + "The process took "+(b-a)+"milliseconds to execute." + "\n" + "("+((b-a)/1000)+" seconds)");

        } catch (RemoteException e) {
            txtView.setText("File not found");
        }

    }

【讨论】:

  • 参见stackoverflow.com/questions/1770010/…,了解如何正确测量经过时间的说明(改用System.nanoTime() - 不是为了精确,而是因为它旨在测量经过时间,不像System.currentTimeMillis())跨度>
  • @Kevin Walker 效果很好,谢谢!不过有一个问题;为什么我第一次请求数据时“过程”比我再次尝试(在同一窗口中)时花费的时间更长?大约 180 毫秒与 55 毫秒。
  • @cssprobs :它很可能缓存在第二轮投票的某个地方,但是如果没有更多关于您正在拉动的内容以及确切的“控制”是什么以及“getFileContents”的方式的详细信息,我无法回答这个问题已实施。
  • @KevinWalker 好的,我想可能是连接已经打开或类似的东西。没关系,按原样工作。
猜你喜欢
  • 2011-10-20
  • 1970-01-01
  • 1970-01-01
  • 2011-05-18
  • 1970-01-01
  • 1970-01-01
  • 2013-01-28
  • 2013-07-14
  • 1970-01-01
相关资源
最近更新 更多