Skip to content

Commit

Permalink
use fastcrc if available
Browse files Browse the repository at this point in the history
  • Loading branch information
tridge committed Apr 26, 2024
1 parent 7b72995 commit 32b8c60
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 2 deletions.
61 changes: 60 additions & 1 deletion generator/mavcrc.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,13 @@
import sys
from builtins import object

try:
import fastcrc
mcrf4xx = fastcrc.crc16.mcrf4xx
except Exception:
mcrf4xx = None

class x25crc(object):
class x25crc_slow(object):
"""CRC-16/MCRF4XX - based on checksum.h from mavlink library"""

def __init__(self, buf=None):
Expand Down Expand Up @@ -39,3 +44,57 @@ def accumulate_str(self, buf):
Provided for backwards compatibility. accumulate now also works on strings.
"""
return self.accumulate(buf)

class x25crc_fast(object):
"""CRC-16/MCRF4XX - based on checksum.h from mavlink library"""
def __init__(self, buf=None):
self.crc = 0xFFFF
if buf is not None:
self.accumulate(buf)

def accumulate(self, buf):
"""add in some more bytes (it also accepts strings)"""
if sys.version_info[0] == 2:
if type(buf) is str:
buf = bytearray(buf)
elif type(buf).__name__ == 'unicode':
# we can't use the identifier unicode in python3
buf = bytearray(buf.encode())
elif type(buf) is str:
buf = bytes(buf.encode())
elif type(buf) is list:
buf = bytes(buf)
self.crc = mcrf4xx(buf, self.crc)

def accumulate_str(self, buf):
"""
Provided for backwards compatibility. accumulate now also works on strings.
"""
return self.accumulate(buf)

if mcrf4xx is not None:
x25crc = x25crc_fast
else:
x25crc = x25crc_slow

if __name__ == "__main__":
import random, time

for i in range(100):
nbytes = random.randint(1000,5000)
b = random.randbytes(nbytes)

t1 = time.time()
slow = x25crc_slow()
t2 = time.time()
slow_t = t2 - t1

t1 = time.time()
c = x25crc()
t2 = time.time()
fast_t = t2 - t1

slow.accumulate(b)
c.accumulate(b)
assert slow.crc == c.crc
print("Speedup %.2f" % (slow_t/fast_t))
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ lxml>=3.6.0
future>=0.15.2
wheel>=0.37.1
setuptools>=42
fastcrc

# dev dependencies:
pytest<=7.4.4
syrupy; python_version>='3.6'
syrupy; python_version>='3.6'

0 comments on commit 32b8c60

Please sign in to comment.