diff options
author | Isaku Yamahata <yamahata@valinux.co.jp> | 2013-04-01 11:58:54 +0900 |
---|---|---|
committer | FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp> | 2013-04-02 12:00:12 +0900 |
commit | e0bcd61f92dbfd1fd9b6acc7387ec531449dcbac (patch) | |
tree | ea9b0ccccd159f00065134d6d96a363ec3e24ace | |
parent | b471e1900fa761a0b7610a012d0e6492aacda6d0 (diff) |
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>
-rw-r--r-- | ryu/lib/packet/packet_utils.py | 9 |
1 files changed, 5 insertions, 4 deletions
diff --git a/ryu/lib/packet/packet_utils.py b/ryu/lib/packet/packet_utils.py index b8f2e058..c36be490 100644 --- a/ryu/lib/packet/packet_utils.py +++ b/ryu/lib/packet/packet_utils.py @@ -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) |