lib/packet/packet_utils: optimize checksum

builtin function, sum, is much faster than for loop.
The result on my machine is as follows

> def main():
>     from timeit import timeit
>     data = bytearray().zfill(1500)
>     print 'new=', timeit(lambda : checksum(data), number=1000)
>     print 'old=', timeit(lambda : checksum_old(data), number=1000)
>
> new= 0.00800108909607
> old= 0.266770124435

Signed-off-by: Isaku Yamahata <yamahata@valinux.co.jp>
Signed-off-by: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
This commit is contained in:
Isaku Yamahata 2013-04-01 11:58:54 +09:00 committed by FUJITA Tomonori
parent b471e1900f
commit e0bcd61f92

View File

@ -13,6 +13,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import array
import socket
import struct
@ -26,10 +27,10 @@ def checksum(data):
if len(data) % 2:
data += '\x00'
s = 0
for i in range(0, len(data), 2):
w = data[i] + (data[i + 1] << 8)
s = carry_around_add(s, w)
data = str(data) # input can be bytearray.
s = sum(array.array('H', data))
s = (s & 0xffff) + (s >> 16)
s += (s >> 16)
return socket.ntohs(~s & 0xffff)