看到有人用 PHP 的 Socket 做出多執行緒的效果,就把那套思路改寫成 ASP 版本。核心觀念其實很樸素:既然 Web 伺服器天生能同時處理多個請求,那我們就在同一個頁面裡,一次對伺服器丟出多個 HTTP 請求,讓它們自己併肩跑。
PHP 那邊要自己開 Socket,ASP 這邊則有現成套好的 Msxml2.XMLHTTP 可以直接用,省下不少工。
先做一次最小驗證——同一個頁面裡寫 a.txt 與 b.txt,看看時間差多少。
<%
startime = timer()
''---------- ASP 模擬多執行緒 ----------''
function runThread()
dim Http
set Http = Server.createobject("Msxml2.XMLHTTP")
Http.open "GET", "thread.ASP?action=b", false
Http.send()
end function
function a()
dim Content, FilePath, MyFile
Content = now() & chr(30) & timer()
FilePath = server.MapPath("a.txt")
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile(FilePath, True)
MyFile.Write(Content)
MyFile.Close
end function
function b()
dim Content, FilePath, MyFile
Content = now() & chr(30) & timer()
FilePath = server.MapPath("b.txt")
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile(FilePath, True)
MyFile.Write(Content)
MyFile.Close
end function
if Request.QueryString("action") = "" then
runThread() ' 先把 b 丟出去
a() ' 自己接著做 a
else
b()
end if
%>
Script Execution Time: <%=fix((timer() - startime) * 1000)%>ms
跑完打開 a.txt 與 b.txt,兩邊寫下的時間幾乎一模一樣——代表兩個工作確實是並行發生的,而不是一個做完才做下一個。
更實際一點的測驗:抓兩個頁面的 HTML。一個用傳統順序寫法(testspeed1.asp),一個用上面的併發寫法(testspeed2.asp)。兩份程式共用的抓取函式如下:
function getHTTPPage(url)
on error resume next
dim http
set http = Server.createobject("Msxml2.XMLHTTP")
Http.open "POST", url, false
Http.send()
if Http.readystate <> 4 then exit function
getHTTPPage = bytes2BSTR(Http.responseBody)
contents = getHTTPPage
Response.Write "<xmp>"
Response.Write(contents)
Response.Write "</xmp>"
set http = nothing
if err.number <> 0 then err.Clear
end function
差別只在最後的呼叫方式。順序版是:
getHTTPPage("https://www.ddvip.com/")
getHTTPPage("https://www.ddvip.com/")
併發版則把其中一次包成函式,先丟到另一個請求去跑:
function runThread()
dim Http
set Http = Server.createobject("Msxml2.XMLHTTP")
Http.open "GET", "thread.ASP?action=b", false
Http.send()
end function
function a() getHTTPPage("https://www.ddvip.com/") end function
function b() getHTTPPage("https://www.ddvip.com/") end function
if Request.QueryString("action") = "" then
runThread()
a()
else
b()
end if
第一組 10 次,抓的是外部網站(兩頁先后順序隨機):
| 次數 | testspeed1(順序)ms | testspeed2(併發)ms |
|---|---|---|
| 1 | 15593 | 13078 |
| 2 | 13343 | 14375 |
| 3 | 12828 | 12515 |
| 4 | 12437 | 12125 |
| 5 | 12109 | 11734 |
| 6 | 12281 | 12140 |
| 7 | 12703 | 12062 |
| 8 | 13468 | 12656 |
| 9 | 12328 | 12187 |
| 10 | 12343 | 12156 |
其中第 2 筆數據明顯異常,網路抖動的影響在這個量級的測試裡很難排除。於是第二组把目標換成 https://127.0.0.1,把網路因素拿掉:
| 次數 | testspeed1(順序)ms | testspeed2(併發)ms |
|---|---|---|
| 11 | 109 | 46 |
| 12 | 62 | 46 |
| 13 | 62 | 48 |
| 14 | 78 | 64 |
| 15 | 62 | 46 |
結論:本機測試下快了一倍上下,外部網站測試則是略快一些。方向是對的,但要看清一件事——
ASP 是單執行緒腳本語言,上面這套做法是「用一個請求去觸發另一個請求」,本質上是併發的 I/O 等待,不是多執行緒運算。它之所以有效,是因為瓶頸通常在等待回應,而等待的時間可以重疊。
因此它有幾個天生的限制:
換句話說,這技巧適合「多個互不依賴、各自耗時的抓取任務」,不適合拿來加速有先後依賴的運算。真正需要平行運算時,還是該用 .NET 的執行緒或 Task 這類正式機制。