Python Tips, Tricks, and Hacks
PyPy is faster than C, again: string formatting
String formatting is probably something you do just about every day in Python, and never think about. It's so easy, just "%d %d" % (i, i) and you're done. No thinking about how to size your result buffer, whether your output has an appropriate NULL byte at the end, or any other details. A C equivalent might be: char x[44]; sprintf(x, "%d %d", i, i); Note that we had to stop for a second and consider how big numbers might get and overestimate the size (44 = length of the biggest number on 64bit (20) + 1 for the sign * 2 + 1 (for the space) + 1 (NUL byte)), it took the authors of this post, fijal and alex, 3 tries to get the math right on this :-) This is fine, except you can't even return x from this function, a more fair comparison might be: char *x = malloc(44 * sizeof(char)); sprintf(x, "%d %d", i, i); x is slightly overallocated in some situations, but that's fine. def main(): for i in xrange(10000000): "%d %d" % (i, i) main() and the C code: Benchmarking the C code: Summary of performance:
tipfy.org
Related:
Related: