C++套接字编程: maximize throughput/bandwidth on localhost (I only get 3 Gbit/s instead of 23GBit/s)

标签 c++ sockets bandwidth throughput

我想创建一个 C++ 服务器/客户端,以最大化本地主机上 TCP 套接字通信的吞吐量。作为准备,我使用了 iperf找出我的 i7 MacBookPro 上的最大带宽是多少。

------------------------------------------------------------
Server listening on TCP port 5001
TCP window size:  256 KByte (default)
------------------------------------------------------------
[  4] local 127.0.0.1 port 5001 connected with 127.0.0.1 port 51583
[  4]  0.0-120.0 sec   329 GBytes  23.6 Gbits/sec

在没有任何调整的情况下,ipref 向我展示了我至少可以达到 23.2 GBit/s。然后我做了我自己的 C++ 服务器/客户端实现,你可以在这里找到完整的代码:https://gist.github.com/1116635

在这段代码中,我基本上在每次读/写操作时都传输了一个 1024 字节的 int 数组。所以我在服务器上的发送循环看起来像这样:

   int n;

   int x[256];

   //fill int array
   for (int i=0;i<256;i++)
   {
       x[i]=i;
   }

   for (int i=0;i<(4*1024*1024);i++)
   {
       n = write(sock,x,sizeof(x));
       if (n < 0) error("ERROR writing to socket");
   }

我在客户端的接收循环看起来是这样的:

int x[256]; 

for (int i=0;i<(4*1024*1024);i++)
{
    n = read(sockfd,x,((sizeof(int)*256)));
    if (n < 0) error("ERROR reading from socket");
}

如标题中所述,运行此(使用 -O3 编译)会导致以下执行时间,约为 3 GBit/s:

./client 127.0.0.1 1234
Elapsed time for Reading 4GigaBytes of data over socket on localhost: 9578ms

我在哪里释放带宽,我做错了什么?同样,完整的代码可以在这里看到:https://gist.github.com/1116635

感谢任何帮助!

最佳答案

  • 使用更大的缓冲区(即减少库/系统调用)
  • 使用异步 API
  • 阅读文档(read/write的返回值不是简单的错误情况,它也代表了读/写的字节数)

关于C++套接字编程: maximize throughput/bandwidth on localhost (I only get 3 Gbit/s instead of 23GBit/s),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6888630/

相关文章:

c++ - 单声道播放单声道 wav 文件

带方法的 C++ 结构,不带方法的 C 声明

c++ - 套接字可用数据读取

python - 在 Python 中为 select.select 操作文件描述符

java - 用java下载文件,如何优化带宽

具有带宽限制的 scp/sftp 的 python 模块

c++ - 在 C++ 中的 const 实例上调用非 const 函数,这可能吗?

c++ - 如何设计Classifier接口(interface)、不同的分类器和数据存储?

c++ - 通过套接字发送数据意外中止

php - 我怎样才能检测到 "Slashdotted"并存活下来?