Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import collections
- import sqlite3
- import timeit
- import os
- import itertools
- ColsCount = 100
- fileName = 'example.db'
- filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), fileName)
- def createTable(conn, rows=100000, cols=ColsCount):
- c = conn.cursor()
- columns = ",".join("Col{0} text".format(x) for x in xrange(cols))
- values = ",".join("\"Value_{0}\"".format(x) for x in xrange(cols))
- c.execute("CREATE TABLE test (id int, {0} )".format(columns))
- for x in xrange(rows):
- c.execute("INSERT INTO test VALUES ({0}, {1})".format(x, values))
- conn.commit()
- Columns = tuple(itertools.chain(('Id',), tuple("Col{0}".format(x) for x in xrange(ColsCount))))
- TupleClass = collections.namedtuple("TupleClass", Columns)
- class RowWrapper(object):
- def __init__(self, values):
- self.Id = values[0]
- for x in xrange(ColsCount):
- setattr(self, "Col{0}".format(x), values[x + 1])
- from django.conf import settings
- settings.configure(DATABASES =
- {
- 'default': {
- 'ENGINE': 'django.db.backends.sqlite3',
- 'NAME': filePath
- }
- }
- )
- from django.db import models
- def buildDjangoObject():
- class DjangoObject(models.Model):
- class Meta:
- app_label = ''
- DjangoObject.Id = models.IntegerField()
- for x in xrange(ColsCount):
- setattr(DjangoObject, "Col{0}".format(x), models.TextField())
- return DjangoObject
- DjangoObject = buildDjangoObject()
- class Tester:
- query = "SELECT * FROM test"
- def __init__(self, conn):
- self.cursor = conn.cursor()
- def test1(self):
- return tuple(row for row in self.cursor.execute(self.query))
- def test2(self):
- return tuple(RowWrapper(row) for row in self.cursor.execute(self.query))
- def test3(self):
- return tuple(TupleClass._make(row) for row in self.cursor.execute(self.query))
- def test4(self):
- return tuple(dict(zip(Columns, row)) for row in self.cursor.execute(self.query))
- def test5(self):
- return tuple(row for row in DjangoObject.objects.raw(self.query))
- if __name__ == '__main__':
- try:
- os.remove(filePath)
- except OSError:
- pass
- conn = sqlite3.connect(filePath)
- createTable(conn)
- tester = Tester(conn)
- t1 = timeit.Timer(tester.test1)
- t2 = timeit.Timer(tester.test2)
- t3 = timeit.Timer(tester.test3)
- t4 = timeit.Timer(tester.test4)
- t5 = timeit.Timer(tester.test5)
- print("Sample 1(tuple): {0}".format(t1.timeit(1)))
- print("Sample 2(RowWrapper): {0}".format(t2.timeit(1)))
- print("Sample 3(TupleClass): {0}".format(t3.timeit(1)))
- print("Sample 4(dict): {0}".format(t4.timeit(1)))
- print("Sample 5(django.model + raw()): {0}".format(t5.timeit(1)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement