Created
July 6, 2011 11:59
-
-
Save aliles/1067062 to your computer and use it in GitHub Desktop.
Test performance of string slice, buffer() and memoryview() for access a substring.
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
"Performance test comparing string slice to buffer() and memoryview()." | |
import os | |
import timeit | |
TESTDATA = os.urandom(16 * 1000) | |
def test_control(s=TESTDATA): | |
"Use a slice to access a substring of s" | |
t = s[2:-1] | |
return len(t) | |
def test_buffer(s=TESTDATA): | |
"Use buffer() built in to access a substring of s" | |
l = len(s) - 3 | |
b = buffer(s, 2, l) | |
return len(b) | |
def test_view(s=TESTDATA): | |
"Use a memoryview() to access a substring of s" | |
m = memoryview(s) | |
v = m[2:-1] | |
return len(v) | |
if __name__=='__main__': | |
loops = 100000 | |
t1 = timeit.Timer('test_control()', 'from __main__ import test_control') | |
print "(control) %.2f usec/pass" % (1e6 * t1.timeit(number=loops)/loops) | |
t2 = timeit.Timer('test_buffer()', 'from __main__ import test_buffer') | |
print "(buffer) %.2f usec/pass" % (1e6 * t2.timeit(number=loops)/loops) | |
t3 = timeit.Timer('test_view()', 'from __main__ import test_view') | |
print "(view) %.2f usec/pass" % (1e6 * t3.timeit(number=loops)/loops) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment