我正在使用HttpListener作为简单的http服务器。我已经通过让HttpListener为每个请求返回字符串“OK”来对req / sec性能进行基准测试 - 这已达到每秒16,000个请求的限制。根据以下代码,我可以做些什么来进一步优化性能?或者我们是否达到Windows Http.sys的极限?
图片上传无效,这里是Visual Studio性能跟踪的链接:
Public Class HTTPServer
Shared Listener As HttpListener = New HttpListener
Public Shared Sub Start()
ServicePointManager.DefaultConnectionLimit = 500
ServicePointManager.Expect100Continue = False
ServicePointManager.MaxServicePoints = 500
Listener.Prefixes.Add("http://localhost/")
Listener.Start()
For i As Integer = 1 To (System.Environment.ProcessorCount * 2)
Dim NewThread As New System.Threading.Thread(AddressOf ListenerThread)
NewThread.Priority = ThreadPriority.Normal
NewThread.IsBackground = True
NewThread.Start()
Next
End Sub
Private Shared Sub ListenerThread()
Dim SyncResult As IAsyncResult
While True
SyncResult = Listener.BeginGetContext(New AsyncCallback(AddressOf ListenerCallback), Listener)
SyncResult.AsyncWaitHandle.WaitOne()
End While
End Sub
Private Shared Sub ListenerCallback(ByVal StateObject As IAsyncResult)
Dim Listener As HttpListener = DirectCast(StateObject.AsyncState, HttpListener)
Dim Context As HttpListenerContext = Listener.EndGetContext(StateObject)
Dim Request As HttpListenerRequest = Context.Request
Dim Response As HttpListenerResponse = Context.Response
Dim ResponseString As String = "OK"
Dim Buffer As Byte() = System.Text.Encoding.UTF8.GetBytes(ResponseString)
Response.ContentLength64 = Buffer.Length
Dim OutputStream As System.IO.Stream = Response.OutputStream
OutputStream.Write(Buffer, 0, Buffer.Length)
OutputStream.Close()
OutputStream.Dispose()
End Sub
End Class
答案 0 :(得分:1)
你可以做的一件事情只是调用Encoding.UTF8.GetBytes("OK")
一次,而不是每次请求。我怀疑它会产生多大的影响,但是如果你在每个请求上都做同样的事情,那么你可能会以你需要的形式得到那个响应。
我还会使用Using
语句而不是显式调用Close和Dispose。这不是一个表现的东西 - 只是一般的好习惯,以避免在有例外的情况下使用未关闭的流的问题。
实际上,你需要才能达到16K以上的QPS吗?你有没有弄清楚你是在受CPU限制还是IO限制?一旦你的程序需要在每个请求上真正做一些真正的工作,我想这会使你在这里做的任何微观优化相形见绌。