在 java(Web 服务)中测量响应时间?

Measure response time in java (web service)?

我正在尝试测量 "process" 的响应时间(我从服务器请求数据然后呈现数据)。我想测量从请求数据(当我按下 "send" 按钮时)到数据显示在我的文本框中所花费的时间。

看起来像这样:

    (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;

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

有什么解决问题的想法吗?

谢谢

看起来很像在创建按钮时设置 a 的值,在单击按钮时设置 b 的值。如果你这样做,那么你会看到你正在看到的结果。 A会保持不变,B会离它越来越远。然后当你重置时,事情会 "go a bit crazy" 因为现在 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");
        }

    }