簡體   English   中英

C++ TCP 套接字發送速度

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM