#!/bin/python """ Demonstration of relative performance of copying an array via the constructor and other methods. """ from array import array import timeit my_array = array('B', 'X' * 1000000) def by_constructor(a): """Copy via the constructor. This is slow!""" return array('B', a) def by_slice(a): """Copy via slicing.""" return a[:] def by_string(a): """Convert to a string and back again.""" b = array('B') b.fromstring(a.tostring()) return b if __name__=='__main__': from timeit import Timer LOOPS = 100 t = Timer("by_constructor(my_array)", "from __main__ import by_constructor, my_array") print "Constructor: ", t.timeit(LOOPS) t = Timer("by_slice(my_array)", "from __main__ import by_slice, my_array") print "Slice: ", t.timeit(LOOPS) t = Timer("by_string(my_array)", "from __main__ import by_string, my_array") print "String: ", t.timeit(LOOPS)