socket本身有一个send函数,这个函数的只能一次发送一个缓冲区,这对于在发送大量数据的时候或者数据包很多的时候就可能导致可能导致系统的低性能,主要原因在于调用太多次的send函数,导致从用户态到核心态的不断切换,而耗费了当前的CPU时钟周期。
那么解决办法就是减少调用send的次数,一种办法就是使用一个大一点的BUFFER,在发送数据的时候将多个数据包的内容COPY到这个BUFFER中,然后一次发送,这样在一定程度上减少了send的调用次数,但需要一定的编码工作。
Windows平台上有一个WSASend函数,可以支持一次发送多个BUFFER的请求,每个被发送的数据被填充到WSABUF结构中,然后传递给WSASend函数同时提供BUF的数量,这样WSASend就能上面的工作而减少send的调用次数,来提高了性能。
实际检验证明,使用WSASend可以提高50%的性能甚至更多
禁用Nagle算法的时机:
"Aside from these problems, disabling the Nagle algorithm almost always causes a program's throughput to degrade. The only time you should disable the algorithm is when some other consideration, such as packet timing, is more important than throughput.
Often, programs that deal with real-time user input will disable the Nagle algorithm to achieve the snappiest possible response, at the expense of network bandwidth. Two examples are X Window servers and multiplayer network games. In these cases, it is more important that there be as little delay between packets as possible than it is to conserve network bandwidth."