码迷,mamicode.com
首页 > 编程语言 > 详细

python几种用法的性能比较1.5

时间:2017-10-18 23:44:09      阅读:485      评论:0      收藏:0      [点我收藏+]

标签:logs   array   sum   nbsp   timeit   imp   data   div   性能   

import timeit

sum_by_for = """
for d in data:
    s += d
"""

sum_by_sum = """
sum(data)
"""

sum_by_numpy_sum = """
import numpy
numpy.sum(data)
"""

def timeit_using_list(n, loops):
    list_setup = """
data =[1] * {}
s = 0
""".format(n)
    print(list result:)
    print(timeit.timeit(sum_by_for, list_setup, number = loops))
    print(timeit.timeit(sum_by_sum, list_setup, number = loops))
    print(timeit.timeit(sum_by_numpy_sum, list_setup, number = loops))

def timeit_using_array(n, loops):
    array_setup = """
import array
data = array.array(‘L‘, [1] * {})
s = 0
""".format(n)
    print(array result:)
    print(timeit.timeit(sum_by_for, array_setup, number = loops))
    print(timeit.timeit(sum_by_sum, array_setup, number = loops))
    print(timeit.timeit(sum_by_numpy_sum, array_setup, number = loops))

def timeit_using_numpy(n, loops):
    numpy_setup = """
import numpy
data = numpy.array([1] * {})
s = 0
""".format(n)
    print(numpy result:)
    print(timeit.timeit(sum_by_for, numpy_setup, number = loops))
    print(timeit.timeit(sum_by_sum, numpy_setup, number = loops))
    print(timeit.timeit(sum_by_numpy_sum, numpy_setup, number = loops))

if __name__ == __main__:
    timeit_using_list(30000, 500)
    timeit_using_array(30000, 500)
    timeit_using_numpy(30000, 500)

 

python几种用法的性能比较1.5

标签:logs   array   sum   nbsp   timeit   imp   data   div   性能   

原文地址:http://www.cnblogs.com/xiaoyingying/p/7689848.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!