Skip to content

Instantly share code, notes, and snippets.

View smarnach's full-sized avatar
🦀

Sven Marnach smarnach

🦀
  • Mozilla
  • Preetz, Germany
View GitHub Profile
import timeit
a = range(10000)
da = set(a)
def list_first():
return 0 in a
def set_first():
return 0 in da
@smarnach
smarnach / gist:784475
Created January 18, 2011 14:10
Be careful with object identity of immutable objects in Python (CPython 2.6.6)
In [1]: a = 256
In [2]: b = 256
In [3]: a is b
Out[3]: True
In [4]: a = 257
In [5]: b = 257
def compose(*funcs):
def comp(x):
for f in reversed(funcs):
x = f(x)
return x
return comp
In [1]: %timeit sum([(0, 0)] * 1000, ())
100 loops, best of 3: 5.01 ms per loop
In [2]: %timeit sum([(0, 0)] * 10000, ())
1 loops, best of 3: 490 ms per loop
In [3]: %timeit sum([(0, 0)] * 100000, ())
1 loops, best of 3: 61.9 s per loop
>>> timeit.repeat("for i in xrange(1000): a.append(i)",
... "from collections import deque; a = deque()", number=10000)
[1.139456033706665, 1.1287789344787598, 1.129647970199585]
>>> timeit.repeat("for i in xrange(1000): a.append(i)", "a = []", number=10000)
[1.1056618690490723, 1.0919761657714844, 1.0903148651123047]
>>> timeit.repeat("a = deque()\nfor i in xrange(10000): a.append(i)\nfor x in a: x",
... "from collections import deque", number=1000)
[1.4415068626403809, 1.4344120025634766, 1.4339849948883057]
>>> timeit.repeat("a = []\nfor i in xrange(10000): a.append(i)\nfor x in a: x", number=1000)
[1.3635458946228027, 1.3510761260986328, 1.3518819808959961]
Python 2.7.2+ (default, Jun 29 2011, 00:07:42)
[GCC 4.6.1 20110616 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class A(object):
... pass
...
>>> A.__doc__ = "doc"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: attribute '__doc__' of 'type' objects is not writable
#include <unistd.h>
#include <stdio.h>
int main(int argc, const char **argv)
{
char c[10240] = {0};
int fd;
sscanf(argv[1] + 8, "%i", &fd); // skip "/dev/fd/"
read(fd, c, 10239);
Tmimings on a Linux box, 32-bit kernel, 32-bit userland
Python version: 2.7 3.1
-s"a=10**20;n=3" "(a>>n)&1" 0.224 usec per loop 0.161 usec per loop
-s"a=10**20;n=3" "not not(a & (1 << n))" 0.155 usec per loop 0.183 usec per loop
-s"a=10**200;n=3" "(a>>n)&1" 0.39 usec per loop 0.303 usec per loop
-s"a=10**200;n=3" "not not(a & (1 << n))" 0.158 usec per loop 0.177 usec per loop
-s"a=10**10;n=3" "(a>>n)&1" 0.223 usec per loop 0.153 usec per loop
-s"a=10**10;n=3" "not not(a & (1 << n))" 0.158 usec per loop 0.18 usec per loop
-s"a=10**9;n=3" "(a>>n)&1" 0.0734 usec per loop 0.152 usec per loop
In [3]: consume = collections.deque(maxlen=0).extend
In [4]: def f(a):
...: consume(x for x in a)
...:
In [5]: def g(a):
...: consume(a)
...: