[英]C++ TCP socket sending speed
我使用简单的锁定 TCP 套接字将消息发送到远程服务器,我遇到的问题是,对于每条消息,发送它需要非常不同的时间。
这是我得到的(一些例子):
Bytes Sent: 217, Time: 34.3336 usec
Bytes Sent: 217, Time: 9.9107 usec
Bytes Sent: 226, Time: 20.1754 usec
Bytes Sent: 226, Time: 38.2271 usec
Bytes Sent: 217, Time: 33.6257 usec
Bytes Sent: 217, Time: 12.7424 usec
Bytes Sent: 217, Time: 21.5912 usec
Bytes Sent: 217, Time: 31.1480 usec
Bytes Sent: 218, Time: 28.3164 usec
Bytes Sent: 218, Time: 13.0963 usec
Bytes Sent: 218, Time: 82.8254 usec
Bytes Sent: 218, Time: 13.0963 usec
Bytes Sent: 227, Time: 30.7941 usec
Bytes Sent: 218, Time: 27.9624 usec
Bytes Sent: 216, Time: 2.1237 usec
Bytes Sent: 218, Time: 12.3884 usec
Bytes Sent: 227, Time: 31.1480 usec
Bytes Sent: 227, Time: 88.4887 usec
Bytes Sent: 218, Time: 93.0901 usec
Bytes Sent: 218, Time: 7.7870 usec
Bytes Sent: 218, Time: 28.3164 usec
Bytes Sent: 227, Time: 89.5505 usec
Bytes Sent: 218, Time: 84.2412 usec
Bytes Sent: 218, Time: 13.8042 usec
Bytes Sent: 227, Time: 99.4612 usec
Bytes Sent: 218, Time: 86.0110 usec
Bytes Sent: 218, Time: 12.3884 usec
Bytes Sent: 218, Time: 87.7807 usec
Bytes Sent: 216, Time: 3.5395 usec
Bytes Sent: 218, Time: 4.6014 usec
Bytes Sent: 218, Time: 36.1034 usec
Bytes Sent: 218, Time: 14.8661 usec
Bytes Sent: 218, Time: 24.0689 usec
Bytes Sent: 218, Time: 18.0517 usec
Bytes Sent: 227, Time: 24.4229 usec
有谁知道为什么会发生这种情况? 为什么发送一条消息需要 3 微秒,而其他 80 微秒?
有没有办法解决这个问题?
注意:我要存档的主要目标是尽快发送每条消息。 我不需要任何同步套接字,至少在它们工作得更快之前。
关于我的工作的一些额外细节:
C++、Visual Studio 2013
我如何打开:
...
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
...
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
...
我如何发送和计算时间:
...
LARGE_INTEGER cT;
QueryPerformanceCounter(&cT);
long long dT = cT.QuadPart;
iBytesSent = send(ConnectSocket, msgFinal, msgFinalLen, 0);
QueryPerformanceCounter(&cT);
dT = cT.QuadPart - dT;
...
另外我正在从其他线程监听这个套接字,我不知道这是否会影响发送:
iResult = recv(ConnectSocket, recvbuf, DEFAULT_BUFLEN, 0);
你的方法无效。 您只是在测量将数据放入发送缓冲区所需的时间。 如果有它的空间,则根本没有网络操作。 如果没有空间,则阻塞直到有空间,这取决于接收器读取已经存在的内容。 所以你看到的是,有时有空间,有时没有,这取决于接收器是否正在阅读和跟上。
如果你想测量往返时间,你需要发送一个时间戳并让对端回显它,然后当你收到它时将它与当前时间进行比较。
您不是在测量“发送”消息所需的时间,而是在测量消息进入 TCP 发送缓冲区所需的时间。 这可能涉及内存分配、锁争用和许多其他事情。 它还可能包括正在安排的另一个进程,从而导致您失去时间片。
您正在测量的是发送呼叫所花费的时间。 它基本上是对套接字层缓冲区的写 (I/O) 操作。
您的进程尝试 i/o 并被阻止 - 一旦 i/o 完成,守护进程就会被唤醒。 您看到的发送呼叫的时间差异包括:
一世。 实际写入时间。
ii. 可中断的睡眠时间 - 因为调度程序不会在 I/O 完成后立即唤醒您的进程。 可能还有另一个进程可能被唤醒。
调整:
一世。 尝试优化发送/接收窗口大小。 这是无需等待 ACK 即可发送的数据量。
访问: 在 C 中设置 TCP 接收窗口并在 Linux 中使用 tcpdump
ii. 您传递给发送调用的缓冲区必须适合窗口大小。 因此 tcp 在实际刷新网络上的数据之前不会等待达到 OPTIMUM 大小。
三、 用于操作系统实现的类似于 TCP_NODELAY 的标志会有所帮助。
四、 重新调整守护进程的 nice 值,以便在阻塞 I/O 调用完成后立即将其唤醒。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.