Created
January 22, 2018 14:13
-
-
Save ManuelBlanc/eb3b5830fe2cc8654417fe27ae46832f to your computer and use it in GitHub Desktop.
This file contains 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/env python | |
import os | |
import django | |
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'onlineshop.settings') | |
django.setup() | |
from django.db.models import Sum, F | |
import random, decimal | |
from placeorder.models import Order, OrderLine | |
from shop.models import Product | |
import timeit | |
p = Product.objects.first() | |
o = Order.objects.first() | |
def make_orderlines(): | |
ol_list = [] | |
for i in range(5000): | |
ol = OrderLine( | |
order = o, | |
product = p, | |
units = random.randint(1, 100), | |
pricePerUnit = decimal.Decimal(random.randint(100, 50000)) / 100, | |
) | |
#ol.save() | |
ol_list.append(ol) | |
OrderLine.objects.bulk_create(ol_list) | |
def func1(): | |
query = OrderLine.objects.all() | |
query = query.annotate(product_cost=F('pricePerUnit') * F('units')) | |
query = query.aggregate(Sum('product_cost')) | |
return query['product_cost__sum'] | |
# select sum(pricePerUnit * units) as product_cost__sum from placeorder_orderline; | |
def func2(): | |
#return sum(map(lambda line: line.getProductCost(), OrderLine.objects.all())) | |
return sum(item.getProductCost() for item in OrderLine.objects.all()) | |
if __name__ == '__main__': | |
import timeit | |
print('Inserting orders ...') | |
make_orderlines() | |
print('{} orders inserted. Summing ...'.format(OrderLine.objects.count())) | |
t1 = timeit.timeit("func1()", setup="from __main__ import func1", number=10) | |
t2 = timeit.timeit("func2()", setup="from __main__ import func2", number=10) | |
print('Method 1: {} seconds'.format(t1)) | |
print('Method 2: {} seconds'.format(t2)) | |
print('Method 2 is ~{} times slower than method 1'.format(int(t2/t1))) | |
OrderLine.objects.all().delete() | |
# len(OrderLine.objects.all() | |
# OrderLine.objects.count() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment