Skip to content
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
76 lines (61 sloc) 1.88 KB
from __future__ import print_function
from optparse import OptionParser
from time import time
from collections import Counter
from bitarray import bitarray
from huffman import (huff_tree, huff_code, write_dot, print_code,
make_tree, iterdecode)
def main():
p = OptionParser("usage: %prog [options] [FILE]")
'-p', '--print',
help="print Huffman code")
'-t', '--tree',
help="store the tree as a .dot file")
opts, args = p.parse_args()
if len(args) == 0:
filename = 'README'
elif len(args) == 1:
filename = args[0]
p.error('only one argument expected')
with open(filename, 'rb') as fi:
plain = bytearray(
if len(args) == 0:
plain *= 1000
t0 = time()
freq = Counter(plain)
print('count: %9.6f sec' % (time() - t0))
t0 = time()
tree = huff_tree(freq)
print('tree: %9.6f sec' % (time() - t0))
if opts.tree:
write_dot(tree, '', 0 in plain)
code = huff_code(tree)
if opts.print:
print_code(freq, code)
if opts.tree:
# create tree from code (no frequencies)
write_dot(make_tree(code), '', 0 in plain)
a = bitarray()
t0 = time()
a.encode(code, plain)
print('C encode: %9.6f sec' % (time() - t0))
# Time the decode function above
t0 = time()
res = bytearray(iterdecode(tree, a))
Py_time = time() - t0
print('Py decode: %9.6f sec' % Py_time)
assert res == plain
# Time the decode method which is implemented in C
t0 = time()
res = bytearray(a.iterdecode(code))
C_time = time() - t0
print('C decode: %9.6f sec' % C_time)
assert res == plain
print('Ratio: %f' % (Py_time / C_time))
if __name__ == '__main__':
You can’t perform that action at this time.