gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:08:14 24 4
gpt4 key购买 nike

我想创建一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com