Advertisement
Guest User

Sample

a guest
Sep 7th, 2012
514
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.83 KB | None | 0 0
  1. import collections
  2. import sqlite3
  3. import timeit
  4. import os
  5. import itertools
  6.  
  7. ColsCount = 100
  8.  
  9. def createTable(conn, rows=100000, cols=ColsCount):
  10.     c = conn.cursor()
  11.     columns = ",".join("Col{0} text".format(x) for x in xrange(cols))
  12.     values = ",".join("\"Value_{0}\"".format(x) for x in xrange(cols))
  13.     c.execute("CREATE TABLE test (id int, {0} )".format(columns))
  14.     for x in xrange(rows):
  15.         c.execute("INSERT INTO test VALUES ({0}, {1})".format(x, values))
  16.     conn.commit()
  17.  
  18. Columns = tuple(itertools.chain(('Id',), tuple("Col{0}".format(x) for x in xrange(ColsCount))))
  19. TupleClass = collections.namedtuple("TupleClass", Columns)
  20.  
  21. class RowWrapper(object):
  22.     def __init__(self, values):
  23.         self.Id = values[0]
  24.         for x in xrange(ColsCount):
  25.             setattr(self, "Col{0}".format(x), values[x + 1])
  26.  
  27. class Tester:
  28.     query = "SELECT * FROM test"
  29.  
  30.     def __init__(self, conn):
  31.         self.cursor = conn.cursor()
  32.  
  33.     def test1(self):
  34.         return tuple(row for row in self.cursor.execute(self.query))
  35.  
  36.     def test2(self):
  37.         return tuple(RowWrapper(row) for row in self.cursor.execute(self.query))
  38.  
  39.     def test3(self):
  40.         return tuple(TupleClass._make(row) for row in self.cursor.execute(self.query))
  41.  
  42. if __name__ == '__main__':
  43.     fileName = 'example.db'
  44.     filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), fileName)
  45.     print(filePath)
  46.     try:
  47.         os.remove(filePath)
  48.     except OSError:
  49.         pass
  50.     conn = sqlite3.connect(filePath)
  51.     createTable(conn)
  52.     tester = Tester(conn)
  53.     t1 = timeit.Timer(tester.test1)
  54.     t2 = timeit.Timer(tester.test2)
  55.     t3 = timeit.Timer(tester.test3)
  56.     print("Sample 1: {0}".format(t1.timeit(1)))
  57.     print("Sample 2: {0}".format(t2.timeit(1)))
  58.     print("Sample 3: {0}".format(t3.timeit(1)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement