Skip to content

Instantly share code, notes, and snippets.

@AntiKnot
Created October 14, 2019 09:38
Show Gist options
  • Select an option

  • Save AntiKnot/c3fb62e245e784a3ba66102f9ddc53fd to your computer and use it in GitHub Desktop.

Select an option

Save AntiKnot/c3fb62e245e784a3ba66102f9ddc53fd to your computer and use it in GitHub Desktop.
测试decimal的性能消耗
import decimal
import time
from functools import reduce
import matplotlib.pyplot as plt
import random
# generate scale number
def scale_random_number(scale):
return [random.uniform(10, 20) for _ in range(scale)]
def decimal_deal(numbers):
return [decimal.Decimal(number) for number in numbers]
#
def operate_time(func, seq):
start = time.process_time()
reduce(func, seq)
end = time.process_time()
res = end - start
return res
def add(a, b):
return a + b
def add_deci(a, b):
return decimal.Decimal(a) + decimal.Decimal(b)
def graph_show():
x = list(range(2, 1000))
numbers_ilst = [scale_random_number(l) for l in x]
numbers_list_pre_decimal = [decimal_deal(numbers) for numbers in numbers_ilst]
y1 = [operate_time(func=add, seq=numbers) for numbers in numbers_ilst]
y2 = [operate_time(func=add_deci, seq=numbers) for numbers in numbers_ilst]
y3 = [operate_time(func=add, seq=numbers) for numbers in numbers_list_pre_decimal]
with plt.style.context('Solarize_Light2'):
l1, = plt.plot(x, y1, label='add')
l2, = plt.plot(x, y2, label='add_decimal')
l3, = plt.plot(x, y3, label='add_decimal_pre')
plt.legend(handles=[l1, l2, l3], labels=['add', 'add_decimal', 'add_decimal_pre'])
plt.title('add')
plt.xlabel('x Scale of numbers', fontsize=14)
plt.ylabel('y Operation time', fontsize=14)
# gcf() before show(), nor will get a blank image
# fig = plt.gcf()
fig = plt.gcf()
plt.show()
# fig.savefig('result.png', dpi=100)
if __name__ == '__main__':
graph_show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment