![](/img/trans.png)
[英]What is the fastest way to sort strings in Python if locale is a non-concern?
[英]Concatenating strings in Python - What is the fastest way
我需要通過套接字發送圖像,並且需要盡快完成。 圖像表示為3d numpy數組。 發送的數據可以超過500000字節。
截至目前,我這樣做:
array_data_type = image.dtype.name
array_shape = image.shape
to_send = array_data_shape + SEPARATOR + cPickle.dumps(array_shape) + SEPARATOR + image.tobytes()
streaming_socket.sendall(to_send)
現在的連接大約需要0.044秒,我希望它更快。 可以更快嗎?
使用join
方法創建單個str
結果,而不是在評估每個+
操作時創建一系列臨時str
對象。
to_send = SEPARATOR.join([array_data_shape, cPickle.dumps(array_shape), image.tobytes()])
您當前的代碼等效於
tmp1 = array_data_shape + SEPARATOR
tmp2 = tmp1 + cPickle.dumps(array_shape)
tmp3 = tmp2 + SEPARATOR
to_send = tmp3 + image.tobytes()
每個+
都必須將其兩個參數都復制到它構造的新str
。 最終結果的長度*的運行時間是二次的,而SEPARATOR.join
是線性的。
*假設您要加入的事物的大小大致相等。 嚴格來說,每個+
的參數大小都是線性的,單個項目被復制的次數與剩余的距離成正比。 假設xi
代表第i
個字符串的大小,則完成的總功為(x1 + x2) + (x1 + x2 + x3) + ... + (x1 + x2 + ... + xn)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.