Skip to content

Instantly share code, notes, and snippets.

@nhoffman
Last active August 29, 2015 13:57
Show Gist options
  • Save nhoffman/9442900 to your computer and use it in GitHub Desktop.
Save nhoffman/9442900 to your computer and use it in GitHub Desktop.
Relative speed of various methods of coercion from int to real in sqlite3
#!/usr/bin/env python
import sqlite3
from random import choice
from timeit import timeit
from itertools import chain
con = sqlite3.connect('test_cast.db', isolation_level=None) # autocommit
cur = con.cursor()
cur.execute('drop table if exists tab')
cur.execute('create table tab (a integer, b integer, c real)')
ints = range(500)
nullrows = ((None, None), (None, 1), (1, None))
randomints = ((choice(ints), choice(ints)) for i in xrange(1000))
cur.executemany('insert into tab (a, b) values (?, ?)',
chain(nullrows, randomints))
con.close()
setup = """\
import sqlite3
con = sqlite3.connect('test_cast.db', isolation_level=None) # autocommit
cur = con.cursor()
"""
cmd = "cur.execute('update tab set c = a*1.0/b')"
print cmd
print timeit(cmd, setup=setup, number=1000)
cmd = "cur.execute('update tab set c = cast(a as real)/b')"
print cmd
print timeit(cmd, setup=setup, number=1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment