【问题标题】:How to improve socket reading performance?如何提高套接字读取性能?
【发布时间】:2012-04-10 08:43:35
【问题描述】:

我一直在测试读取服务器套接字输入流的性能。我发现阅读本身有大约 9000 纳秒(9 我们)的延迟。我怎样才能提高它的性能? 我已经尝试过 JAVA 默认缓冲区大小和比这更大的东西。但它的性能并没有太大变化。在这种情况下,我计算了来自客户端的每 1600 个样本。

大部分延迟都出现在这一行:

inputLine = in.readLine();

这里是读取线程的代码:

PrintWriter out = new PrintWriter(door.getOutputStream(), true);            
BufferedReader in = new BufferedReader(new InputStreamReader(door.getInputStream()), 10240);           

File file = new File(this.storageDirectory);
BufferedWriter save = new BufferedWriter(new FileWriter(file));

String inputLine = null;

while(Switch)
{
    inputLine = in.readLine(); //I found ~9000 ns delay in this line.
    save.write(inputLine);


    if(iCounter==0)
        StartTime = System.nanoTime();                   

    iCounter++;                      


    if(iCounter>=1600) //need to store them.
    {
        EndTime = System.nanoTime();
        TimeTick = (EndTime - StartTime)/1600;
        System.out.println("TimeTick is [ns]: " + TimeTick);                    
        iCounter = 0;
    }
 }

结果如下:

TimeTick is [ns]: 9241
TimeTick is [ns]: 9941
TimeTick is [ns]: 6535
.....

这是没有'inputLine = in.readLine();'的结果

TimeTick is [ns]: 0
TimeTick is [ns]: 0
TimeTick is [ns]: 1
......

如何提高阅读性能?客户端只是根据请求发送随机双点值。

谢谢,

【问题讨论】:

    标签: java time


    【解决方案1】:
    String inputLine = null;
    
    while (...) {
        ...
        inputLine = in.readLine(); //I found ~9000 ns delay in this line.
        save.write(inputLine);
        ...
    }
    

    如果你注释掉读取的行,你就没有什么可写的了,所以实际上你注释掉了这两行,不是吗?

    如果您有一些 save.write 在每次迭代中写入的默认字符串,您的微基准测试(开始时似乎有点狡猾)可能会显示更好的信息。

    好的和相关的问题和答案:

    【讨论】:

    • 这样做的目的是使服务器响应迅速。我需要从使用 1 kHz 触发器生成 1600 个样本的客户端读取和写入。那么样本的每个时间刻度必须是 0.001/1600 = 0.000625 ms (0.625 us)。因此,9000 ns (9 us) 是一个相当大的值。
    • 我明白了。祝您优化成功。
    • @user1098761 这是带宽的 1.5%。这真的是一个很大的价值吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-26
    • 2019-04-05
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多