Created
May 8, 2015 18:11
-
-
Save fukubaya/83d2a59d12b27ff5f7e8 to your computer and use it in GitHub Desktop.
Comparison of exec time for a list generation in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
# | |
# bench.py | |
# | |
# Created by FUKUBAYASHI Yuichiro on 2015/05/09 | |
# Copyright (c) 2015, FUKUBAYASHI Yuichiro | |
# | |
# last update: <2015/05/09 02:42:22> | |
# | |
import sys | |
from optparse import OptionParser | |
import time | |
from array import array | |
# list all 0 | |
def list_0_append(n): | |
xs = [] | |
for i in xrange(n): | |
xs.append(0) | |
return xs | |
def list_0_comp(n): | |
return [0 for i in xrange(n)] | |
def list_0_multi(n): | |
return [0] * n | |
def list_0_array(n): | |
return array('I', [0 for i in xrange(n)]) | |
def list_0_range(n): | |
xs = range(n) | |
for i in xrange(n): | |
xs[i] = 0 | |
return xs | |
# list i | |
def list_i_append(n): | |
xs = [] | |
for i in xrange(n): | |
xs.append(i) | |
return xs | |
def list_i_comp(n): | |
return [i for i in xrange(n)] | |
def list_i_multi(n): | |
xs = [0] * n | |
for i in xrange(n): | |
xs[i] = i | |
return xs | |
def list_i_array(n): | |
return array('I', [i for i in xrange(n)]) | |
def list_i_range(n): | |
return range(n) | |
# measure exec time | |
def exec_time(n, n_sample, func): | |
t = 0.0 | |
for i in range(n_sample): | |
start = time.clock() | |
func(n) | |
end = time.clock() | |
t += (end - start) | |
return t / n_sample | |
def main(options, args): | |
n = options.n | |
n_sample = 5 | |
print "--Python version--" | |
print sys.version | |
print "--list_0--" | |
for f in [list_0_append, | |
list_0_comp, | |
list_0_multi, | |
list_0_array, | |
list_0_range]: | |
print "%s(%d) in %f(s)" % (f.__name__, | |
n, | |
exec_time(n, n_sample, f)) | |
print "--list_i--" | |
for f in [list_i_append, | |
list_i_comp, | |
list_i_multi, | |
list_i_array, | |
list_i_range]: | |
print "%s(%d) in %f(s)" % (f.__name__, | |
n, | |
exec_time(n, n_sample, f)) | |
if __name__ == '__main__': | |
parser = OptionParser() | |
parser.add_option('-n', action='store', type='int', default=10000) | |
options, args = parser.parse_args() | |
main(options, args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment