Last active
December 26, 2015 18:59
-
-
Save loic/7198193 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
# $ PYTHONPATH=.. ./manage.py test | |
# Creating test database for alias 'default'... | |
# test_list_backed_lookup | |
# 3.81117606163 | |
# .test_manager_backed_lookup | |
# 6.57371211052 | |
# . | |
# ---------------------------------------------------------------------- | |
# Ran 2 tests in 12.099s | |
from timeit import Timer | |
from django.db import models | |
from django.db.models import Prefetch | |
from django.test import TestCase | |
class Book(models.Model): | |
title = models.CharField(max_length=100) | |
class Author(models.Model): | |
author = models.CharField(max_length=100) | |
books = models.ManyToManyField(Book) | |
class Benchmark(TestCase): | |
def setUp(self): | |
for i in range(0, 100): | |
a = Author.objects.create(author="Author %s" % i) | |
bset = set() | |
for j in range(0, 20): | |
b = Book.objects.create(title="Title %s" % j) | |
bset.add(b) | |
a.books = bset | |
def test_manager_backed_lookup(self): | |
def prefetch(): | |
for a in Author.objects.prefetch_related('books'): | |
list(a.books.all()) | |
timer = Timer(prefetch) | |
print('test_manager_backed_lookup') | |
print(timer.timeit(number=100)) | |
def test_list_backed_lookup(self): | |
def prefetch(): | |
for a in Author.objects.prefetch_related(book_list=Prefetch('books')): | |
list(a.book_list) | |
timer = Timer(prefetch) | |
print('test_list_backed_lookup') | |
print(timer.timeit(number=100)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment