Re: while True or while 1
On 01/22/2012 10:55 PM, alex23 wrote: On Jan 23, 2:05 am, Dan Sommersd...@tombstonezero.net wrote: As per a now-ancient suggestion on this mailing list (I believe it was by Tim Peters), I've also been known to use a non-empty, literal Python string as a self-documenting, forever-True value in the typical loop-and-a- half cnstruct: while the temperature is too big: I don't think I've ever encountered this before, but I like it :) Cheers! I do something similar when there's a portion of code that should never be reached: assert(reason why I cannot get here) -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
Dave Angel d...@davea.name writes: I do something similar when there's a portion of code that should never be reached: assert(reason why I cannot get here) Shouldn't that be assert False, reason why I cannot get here? -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On 2012-01-21, Erik Max Francis m...@alcyone.com wrote: Chris Angelico wrote: On Sun, Jan 22, 2012 at 12:47 AM, Andrea Crotti andrea.crott...@gmail.com wrote: So I tried to do the following, and the result is surprising. For what I can see it looks like the interpreter can optimize away the 1 boolean conversion while it doesn't with the True, the opposite of what I supposed. Anyone can explain me why is that, or maybe is my conclusion wrong? In Python 3, they compile to the same code, because 'True' is a keyword. In Python 2, you can reassign True to be 0. Why this should concern anyone, I don't know; I don't think it does concern anybody (except the compiler, who treats all identifiers the same). [...] The real reason people still use the `while 1` construct, I would imagine, is just inertia or habit, That's certain why I do it. It's left over from the days when C and Python didn't have symbolic boolean constants. rather than a conscious, defensive decision. If it's the latter, it's a case of being _way_ too defensive. -- Grant Edwards grant.b.edwardsYow! Hmmm ... A hash-singer at and a cross-eyed guy were gmail.comSLEEPING on a deserted island, when ... -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
Il 21 gennaio 2012 22:13, Erik Max Francis m...@alcyone.com ha scritto: The real reason people still use the `while 1` construct, I would imagine, is just inertia or habit, rather than a conscious, defensive decision. If it's the latter, it's a case of being _way_ too defensive. It's also because while 1 is faster: import time t = time.time() x = 0 while 1: x += 1 if x 1000: break print(time.time() - t) while True: 1.41121292114 while 1: 1.07101011276 Most of the times tha't won't make any noticeable difference, but it's also true that certain while loops are going to iterate milions of times. Think about receiving a 10 GB file by using a socket. You'd tipically have something like this: while 1: chunk = sock.recv(1024): if not chunk: break ... Now, that's a case where I (personally) want to explicitly use while 1 instead of while True. --- Giampaolo http://code.google.com/p/pyftpdlib/ http://code.google.com/p/psutil/ http://code.google.com/p/pysendfile/ -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On Mon, Jan 23, 2012 at 9:41 AM, Giampaolo Rodolà g.rod...@gmail.com wrote: Il 21 gennaio 2012 22:13, Erik Max Francis m...@alcyone.com ha scritto: The real reason people still use the `while 1` construct, I would imagine, is just inertia or habit, rather than a conscious, defensive decision. If it's the latter, it's a case of being _way_ too defensive. It's also because while 1 is faster: That's because, as has already been pointed out in the thread, the compiler is able to store the 1 literal with the code, whereas True requires a name lookup. If you try the same timing test in Python 3, you will find that there is no longer any difference. Think about receiving a 10 GB file by using a socket. You'd tipically have something like this: while 1: chunk = sock.recv(1024): if not chunk: break ... Now, that's a case where I (personally) want to explicitly use while 1 instead of while True. I disagree. 10 GB in 1 KB chunks is going to be 10,000,000 loops, which as you just demonstrated above, carries an overhead of about 0.4 seconds if we use True instead of 1. That's entirely trivial compared to the time needed to actually transfer the file. Moreover, unless you're doing a significant amount of processing on the file as you read it, a socket-reading loop like that is likely to be IO-bound -- which means that after the while 1 check, the process is usually going to go to sleep anyway as it waits for more data. In that case, the extra 40 nanoseconds for the name lookup makes no difference at all, as the process wasn't going to do anything useful with those cycles anyway. Actually, I have a hard time envisioning a case where the difference between while 1 and while True in Python 2.x is worth caring about. At the point where it might actually start to be noticeable (say around 100 million iterations), there are surely higher-priority optimizations to be made, including rewriting parts of the program in C. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil -- Donald Knuth Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On 01/23/2012 08:28 AM, Hrvoje Niksic wrote: Dave Angeld...@davea.name writes: I do something similar when there's a portion of code that should never be reached: assert(reason why I cannot get here) Shouldn't that be assert False, reason why I cannot get here? You caught me in a typo. If it's in python there should be a not there, and if it's in C, a bang. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On 01/23/2012 11:39 AM, Ian Kelly wrote: We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil -- Donald Knuth To play devil's advocate for a moment, if you have the choice between two ways of writing something, A and B, where both are basically the same in terms of difficulty to write, difficulty to maintain, and difficulty to understand, but A is faster than B, even if just by a hair, why NOT write A? It's like 'iter++' vs '++iter' in a C++ for loop. For ints, or for some iterators with optimization, it makes no difference. But the latter will be faster in debug builds, and *might* be faster in release builds if you have a complicated iterator. So why NOT make for(...; ...; ++i) the typical way of writing a for loop? In the Python world, is 'while 1' any harder to understand than 'while True'? I'm about as staunch a supporter as you'll find for the idea that 'while 1' should throw an exception, and even *I* think that 'while 1' is about the least-offensive idiom out there. If 'while 1' throws you off, I'd hate to see what you do when you learn that Python accepts loops like 'while x' where the condition evaluates to true if x is a non-zero integer and false if x is 0. All that said, I like the 'while stuff to do' idea. Evan -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
Giampaolo Rodolà wrote: Il 21 gennaio 2012 22:13, Erik Max Francis m...@alcyone.com ha scritto: The real reason people still use the `while 1` construct, I would imagine, is just inertia or habit, rather than a conscious, defensive decision. If it's the latter, it's a case of being _way_ too defensive. It's also because while 1 is faster: ... while True: 1.41121292114 while 1: 1.07101011276 Most of the times tha't won't make any noticeable difference, but it's also true that certain while loops are going to iterate milions of times. Think about receiving a 10 GB file by using a socket. You'd tipically have something like this: while 1: chunk = sock.recv(1024): if not chunk: break ... Now, that's a case where I (personally) want to explicitly use while 1 instead of while True. Such a loop would obviously be I/O-bound, not CPU-bound. So changing the form of the while loop would make minimal difference to its overall performance. It'd be spending the vast majority of its time blocked at the OS socket level, not executing the condition of the while loop. As with most of these things, if one is this worried about performance, then either Python was the wrong choice to begin with, or there's a good chance that you're worried about something that isn't actually where the bottleneck is in the first place. -- Erik Max Francis m...@alcyone.com http://www.alcyone.com/max/ San Jose, CA, USA 37 18 N 121 57 W AIM/Y!M/Jabber erikmaxfrancis Think twice before you speak to a friend in need. -- Ambrose Bierce -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
Il 23 gennaio 2012 20:12, Erik Max Francis m...@alcyone.com ha scritto: Giampaolo Rodolà wrote: Il 21 gennaio 2012 22:13, Erik Max Francis m...@alcyone.com ha scritto: The real reason people still use the `while 1` construct, I would imagine, is just inertia or habit, rather than a conscious, defensive decision. If it's the latter, it's a case of being _way_ too defensive. It's also because while 1 is faster: ... while True: 1.41121292114 while 1: 1.07101011276 Most of the times tha't won't make any noticeable difference, but it's also true that certain while loops are going to iterate milions of times. Think about receiving a 10 GB file by using a socket. You'd tipically have something like this: while 1: chunk = sock.recv(1024): if not chunk: break ... Now, that's a case where I (personally) want to explicitly use while 1 instead of while True. Such a loop would obviously be I/O-bound, not CPU-bound. So changing the form of the while loop would make minimal difference to its overall performance. It'd be spending the vast majority of its time blocked at the OS socket level, not executing the condition of the while loop. As with most of these things, if one is this worried about performance, then either Python was the wrong choice to begin with, or there's a good chance that you're worried about something that isn't actually where the bottleneck is in the first place. -- Erik Max Francis m...@alcyone.com http://www.alcyone.com/max/ San Jose, CA, USA 37 18 N 121 57 W AIM/Y!M/Jabber erikmaxfrancis Think twice before you speak to a friend in need. -- Ambrose Bierce -- http://mail.python.org/mailman/listinfo/python-list Obviously, you're right. I picked up the wrong example. My point is 1.41121292114 vs 1.07101011276 *might* make some difference in certain cases. I just can't come up with a good example where that would be justified. =) --- Giampaolo http://code.google.com/p/pyftpdlib/ http://code.google.com/p/psutil/ http://code.google.com/p/pysendfile/ -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On 01/23/2012 06:05 PM, Evan Driscoll wrote: To play devil's advocate for a moment, if you have the choice between two ways of writing something, A and B, where both are basically the same in terms of difficulty to write, difficulty to maintain, and difficulty to understand, but A is faster than B, even if just by a hair, why NOT write A? It's like 'iter++' vs '++iter' in a C++ for loop. For ints, or for some iterators with optimization, it makes no difference. But the latter will be faster in debug builds, and *might* be faster in release builds if you have a complicated iterator. So why NOT make for(...; ...; ++i) the typical way of writing a for loop? In the Python world, is 'while 1' any harder to understand than 'while True'? I'm about as staunch a supporter as you'll find for the idea that 'while 1' should throw an exception, and even *I* think that 'while 1' is about the least-offensive idiom out there. If 'while 1' throws you off, I'd hate to see what you do when you learn that Python accepts loops like 'while x' where the condition evaluates to true if x is a non-zero integer and false if x is 0. All that said, I like the 'while stuff to do' idea. Evan I think it's not the same, iter++ or ++iter is exactly the same in terms of readability, so of course if one might be a bit faster, it should be used. while 1 works because the 1 is converted to boolean automatically, but why not just writing a boolean in the first place? It's not bad of course but to me it's not very Pythonic, and reminds me C. At that point I also prefer the while 'might be long loop' idea, which at least adds some value *and* it might be very slightly faster too. -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
在 2012年1月24日星期二UTC+8上午4时50分11秒,Andrea Crotti写道: On 01/23/2012 06:05 PM, Evan Driscoll wrote: To play devil's advocate for a moment, if you have the choice between two ways of writing something, A and B, where both are basically the same in terms of difficulty to write, difficulty to maintain, and difficulty to understand, but A is faster than B, even if just by a hair, why NOT write A? It's like 'iter++' vs '++iter' in a C++ for loop. For ints, or for some iterators with optimization, it makes no difference. But the latter will be faster in debug builds, and *might* be faster in release builds if you have a complicated iterator. So why NOT make for(...; ...; ++i) the typical way of writing a for loop? In the Python world, is 'while 1' any harder to understand than 'while True'? I'm about as staunch a supporter as you'll find for the idea that 'while 1' should throw an exception, and even *I* think that 'while 1' is about the least-offensive idiom out there. If 'while 1' throws you off, I'd hate to see what you do when you learn that Python accepts loops like 'while x' where the condition evaluates to true if x is a non-zero integer and false if x is 0. All that said, I like the 'while stuff to do' idea. Evan I think it's not the same, iter++ or ++iter is exactly the same in terms of readability, so of course if one might be a bit faster, it should be used. while 1 works because the 1 is converted to boolean automatically, but why not just writing a boolean in the first place? It's not bad of course but to me it's not very Pythonic, and reminds me C. At that point I also prefer the while 'might be long loop' idea, which at least adds some value *and* it might be very slightly faster too. A fake generator that can't be cascaded for more processing can be called an iterator by the definition of an iterator. But that is miss-leading in implementing silly trivial non-qualified iterators. -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On Mon, 23 Jan 2012 20:50:11 +, Andrea Crotti wrote: while 1 works because the 1 is converted to boolean automatically, but why not just writing a boolean in the first place? You have misunderstood Python's truth model. It is similar to languages like Javascript and PHP, where EVERY object without exception has a truth value. Python does not convert 1 to a boolean, because that would be pointless and silly. Bools True and False in Python are no more privileged than anything else, in fact they are *less* privileged in Python 2 because they are merely built-in names which can be re-bound, not reserved words like None. In Python 2, the peephole optimizer can optimize away constants such as 1. But 1 itself is not special -- any non-zero int, or non-empty string, is also a true-ish value: from dis import dis dis(compile('if 42: spam', '', 'exec')) 1 0 LOAD_NAME0 (spam) 3 POP_TOP 4 LOAD_CONST 0 (None) 7 RETURN_VALUE While True is just a name, and therefore needs to be looked up at runtime like every other name: dis(compile('if True: spam', '', 'exec')) 1 0 LOAD_NAME0 (True) 3 JUMP_IF_FALSE8 (to 14) 6 POP_TOP 7 LOAD_NAME1 (spam) 10 POP_TOP 11 JUMP_FORWARD 1 (to 15) 14 POP_TOP 15 LOAD_CONST 0 (None) 18 RETURN_VALUE In Python 3, True and False become constants, like None, and the peephole optimizer can treat them like 42 or 0 or -3. Nevertheless, the important factor is not the optimizer, but the JUMP_IF_FALSE op-code. That accepts *any* Python object, not just True and False: dis(compile('if [1, 2, 3]: spam', '', 'exec')) 1 0 LOAD_CONST 0 (1) 3 LOAD_CONST 1 (2) 6 LOAD_CONST 2 (3) 9 BUILD_LIST 3 12 JUMP_IF_FALSE8 (to 23) 15 POP_TOP 16 LOAD_NAME0 (spam) 19 POP_TOP 20 JUMP_FORWARD 1 (to 24) 23 POP_TOP 24 LOAD_CONST 3 (None) 27 RETURN_VALUE Note that a sufficiently clever peephole optimizer could have recognised that [1,2,3] is a true value, just as 42 is a true value. But that's besides the point: what is important is that any object is true-ish or false-ish. The only advantages to True and False are: (1) They satisfy programmers from Pascal and other languages which insist on actual Boolean types in comparisons. You can recognise these people who haven't quite yet grasped Python's model, and are still writing Pascal or Java, because they write unpythonic code which does unnecessary work, such as if bool(x) instead of just if x. Worse are the ones who write if bool(x) is True, because they don't even understand boolean logic. (2) They are self-documenting, especially for return values. If a function returns 0 or 1, there may be some uncertainty whether that should be understood as a number, or a flag. By returning False or True, it self-documents that it is a flag. (3) It avoids people having to define their own true/false values, with a multitude of spellings, in every library and project that uses them. If your branch (while loop or if/elif clause) is taking a constant literal, you probably should prefer True/False over any other object simply because it is more readable and clear as to your intention. But it is no big deal if you prefer 1/0 instead. If you branch over an arbitrary named object, like while x, there is no point in writing that as while bool(x). All that does is indicate that you are uncomfortable with, or don't understand, Python's truth model, and perform an extra, unnecessary, name lookup and function call. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On Sun, 22 Jan 2012 05:25:25 +, Steven D'Aprano wrote: Or they've been writing Python code since before version 2.2 when True and False were introduced, and so they are used to the while 1 idiom and never lost the habit. That would be me. As per a now-ancient suggestion on this mailing list (I believe it was by Tim Peters), I've also been known to use a non-empty, literal Python string as a self-documenting, forever-True value in the typical loop-and-a- half cnstruct: while the temperature is too big: temperature = get_temperature() if temperature = threshold: break process_temperature(temperature) This way, even though the loop condition is buried inside the loop (which could be longer than four lines), it is apparent as soon as I encounter the loop. With the advent of the with statement, though, these loops are slowly disappearing. -- Dan -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On 22/01/2012 16:05, Dan Sommers wrote: On Sun, 22 Jan 2012 05:25:25 +, Steven D'Aprano wrote: Or they've been writing Python code since before version 2.2 when True and False were introduced, and so they are used to the while 1 idiom and never lost the habit. That would be me. As per a now-ancient suggestion on this mailing list (I believe it was by Tim Peters), I've also been known to use a non-empty, literal Python string as a self-documenting, forever-True value in the typical loop-and-a- half cnstruct: while the temperature is too big: temperature = get_temperature() if temperature= threshold: break process_temperature(temperature) This way, even though the loop condition is buried inside the loop (which could be longer than four lines), it is apparent as soon as I encounter the loop. And the output of dis shows that it's optimised to a forever loop. With the advent of the with statement, though, these loops are slowly disappearing. -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On Jan 23, 2:05 am, Dan Sommers d...@tombstonezero.net wrote: As per a now-ancient suggestion on this mailing list (I believe it was by Tim Peters), I've also been known to use a non-empty, literal Python string as a self-documenting, forever-True value in the typical loop-and-a- half cnstruct: while the temperature is too big: I don't think I've ever encountered this before, but I like it :) Cheers! -- http://mail.python.org/mailman/listinfo/python-list
while True or while 1
I see sometimes in other people code while 1 instead of while True. I think using True is more pythonic, but I wanted to check if there is any difference in practice. So I tried to do the following, and the result is surprising. For what I can see it looks like the interpreter can optimize away the 1 boolean conversion while it doesn't with the True, the opposite of what I supposed. Anyone can explain me why is that, or maybe is my conclusion wrong? def f1(): while 1: pass def f2(): while True: pass In [10]: dis.dis(f) 2 0 SETUP_LOOP 3 (to 6) 3 3 JUMP_ABSOLUTE3 6 LOAD_CONST 0 (None) 9 RETURN_VALUE In [9]: dis.dis(f1) 2 0 SETUP_LOOP 10 (to 13) 3 LOAD_GLOBAL 0 (True) 6 POP_JUMP_IF_FALSE 12 3 9 JUMP_ABSOLUTE3 12 POP_BLOCK 13 LOAD_CONST 0 (None) 16 RETURN_VALUE -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
Actually there was the same question here (sorry should have looked before) http://stackoverflow.com/questions/3815359/while-1-vs-for-whiletrue-why-is-there-a-difference And I think the main reason is that 1 is a constant while True is not such and can be reassigned. -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On Sun, Jan 22, 2012 at 12:47 AM, Andrea Crotti andrea.crott...@gmail.com wrote: So I tried to do the following, and the result is surprising. For what I can see it looks like the interpreter can optimize away the 1 boolean conversion while it doesn't with the True, the opposite of what I supposed. Anyone can explain me why is that, or maybe is my conclusion wrong? In Python 3, they compile to the same code, because 'True' is a keyword. In Python 2, you can reassign True to be 0. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
Probably because of the fact it is possible to set True equal to False and consequently then invalidate loop logic as presented below: True = False while True: ... On the other hand `1' will always be evaluated as a constant. Don't know, just guessing. Matteo On Jan/21, Andrea Crotti wrote: I see sometimes in other people code while 1 instead of while True. I think using True is more pythonic, but I wanted to check if there is any difference in practice. So I tried to do the following, and the result is surprising. For what I can see it looks like the interpreter can optimize away the 1 boolean conversion while it doesn't with the True, the opposite of what I supposed. Anyone can explain me why is that, or maybe is my conclusion wrong? def f1(): while 1: pass def f2(): while True: pass In [10]: dis.dis(f) 2 0 SETUP_LOOP 3 (to 6) 3 3 JUMP_ABSOLUTE3 6 LOAD_CONST 0 (None) 9 RETURN_VALUE In [9]: dis.dis(f1) 2 0 SETUP_LOOP 10 (to 13) 3 LOAD_GLOBAL 0 (True) 6 POP_JUMP_IF_FALSE 12 3 9 JUMP_ABSOLUTE3 12 POP_BLOCK 13 LOAD_CONST 0 (None) 16 RETURN_VALUE -- http://mail.python.org/mailman/listinfo/python-list -- http://www.matteolandi.net -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
Chris Angelico wrote: On Sun, Jan 22, 2012 at 12:47 AM, Andrea Crotti andrea.crott...@gmail.com wrote: So I tried to do the following, and the result is surprising. For what I can see it looks like the interpreter can optimize away the 1 boolean conversion while it doesn't with the True, the opposite of what I supposed. Anyone can explain me why is that, or maybe is my conclusion wrong? In Python 3, they compile to the same code, because 'True' is a keyword. In Python 2, you can reassign True to be 0. Why this should concern anyone, I don't know; someone who's rebound `True` or `False` to evaluate to something other than true and false, respectively, is only doing so to be difficult (or very foolish). One of the principles of Python programming is that We're All Adults Here, so this kind of defensive programming is really superfluous. In other words, yes, it's quite reasonable to assume that (even in Python 2) `True` is bound to something which is, in fact, true. The real reason people still use the `while 1` construct, I would imagine, is just inertia or habit, rather than a conscious, defensive decision. If it's the latter, it's a case of being _way_ too defensive. -- Erik Max Francis m...@alcyone.com http://www.alcyone.com/max/ San Jose, CA, USA 37 18 N 121 57 W AIM/Y!M/Jabber erikmaxfrancis Ambition can creep as well as soar. -- Edmund Burke -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
Andrea Crotti wrote: I see sometimes in other people code while 1 instead of while True. I think using True is more pythonic, but I wanted to check if there is any difference in practice. No (with the exception of `True` and `False` being rebinable in Python 2). The idiomatic `while 1` notation comes from back in the pre-Boolean days. In any reasonably modern implementation, `while True` is more self-documenting. I would imagine the primary reason people still do it, any after-the-fact rationalizations aside, is simply habit. -- Erik Max Francis m...@alcyone.com http://www.alcyone.com/max/ San Jose, CA, USA 37 18 N 121 57 W AIM/Y!M/Jabber erikmaxfrancis Ambition can creep as well as soar. -- Edmund Burke -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On Sun, Jan 22, 2012 at 8:13 AM, Erik Max Francis m...@alcyone.com wrote: Why this should concern anyone, I don't know; someone who's rebound `True` or `False` to evaluate to something other than true and false, respectively, is only doing so to be difficult (or very foolish). One of the principles of Python programming is that We're All Adults Here, so this kind of defensive programming is really superfluous. In other words, yes, it's quite reasonable to assume that (even in Python 2) `True` is bound to something which is, in fact, true. Yes, but there's no special code in the compiler to handle True - it's just a name like any other. It finds a token that looks like a name, so it puts a name lookup into the bytecode. The real reason people still use the `while 1` construct, I would imagine, is just inertia or habit, rather than a conscious, defensive decision. If it's the latter, it's a case of being _way_ too defensive. Ehh, 'while 1' is shorter too. I reckon some people are just lazy :) Or have come from C where 'while (1)' is the normal thing to do. According to the Eliza Effect, supporting 'while 1' is a Good Thing. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On Sun, 22 Jan 2012 09:13:23 +1100, Chris Angelico wrote: On Sun, Jan 22, 2012 at 8:13 AM, Erik Max Francis m...@alcyone.com wrote: Why this should concern anyone, I don't know; someone who's rebound `True` or `False` to evaluate to something other than true and false, respectively, is only doing so to be difficult (or very foolish). One of the principles of Python programming is that We're All Adults Here, so this kind of defensive programming is really superfluous. In other words, yes, it's quite reasonable to assume that (even in Python 2) `True` is bound to something which is, in fact, true. Yes, but there's no special code in the compiler to handle True - it's just a name like any other. It finds a token that looks like a name, so it puts a name lookup into the bytecode. The real reason people still use the `while 1` construct, I would imagine, is just inertia or habit, rather than a conscious, defensive decision. If it's the latter, it's a case of being _way_ too defensive. Ehh, 'while 1' is shorter too. I reckon some people are just lazy :) Or they've been writing Python code since before version 2.2 when True and False were introduced, and so they are used to the while 1 idiom and never lost the habit. In Python 2, while 1 is a micro-optimization over while True, because there is no need to look-up the name True. For extremely tight loops, that may make a difference. In Python 3, there is no longer any real difference: py dis(compile('while 1: pass', '', 'exec')) 1 0 SETUP_LOOP 3 (to 6) 3 JUMP_ABSOLUTE3 6 LOAD_CONST 0 (None) 9 RETURN_VALUE py dis(compile('while True: pass', '', 'exec')) 1 0 SETUP_LOOP 3 (to 6) 3 JUMP_ABSOLUTE3 6 LOAD_CONST 0 (None) 9 RETURN_VALUE Or perhaps they just like the look of while 1. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
hehehehehehe... On 17/12/2010 2.01, Steven D'Aprano wrote: On Thu, 16 Dec 2010 23:34:21 +, BartC wrote: In terms of a more realistic function (admittedly still a little contrived, as the loop would be written differently), I tried this: def p2(n): p=1 while True: if n=p: return p p=1 return 0 for i in xrange(100): x=p2(i) p2() calculates the smallest power of 2= it's operand. Using while True as shown, it took 3.4 seconds. Using While 1, it took 2.6 seconds (Python 2.5). Right. And a saving of 0.8 microseconds per iteration is a micro- optimization which is likely to be invisible in any real situation. I mean, yes, you saved almost an entire second. Wow. Save another 179 of them and you'll almost have enough time to make yourself a coffee. Bart, we get it. Nobody denies that the optimization is real, only that it is generally meaningful. Who cares whether it takes 2 seconds or 4 seconds to generate one million results if the rest of the application takes 3 minutes to run? *If* your application is such that saving 0.8 microseconds per iteration actually is useful, AND your loop has to be written as a while True loop, then this *may* be a useful micro-optimization to save 0.8 microseconds per iteration. That's a vanishingly tiny proportion of all code written. If your code happens to meet those conditions, then by all means use while 1. Or move to Python 3, where while True has the same optimization performed. But in general, such micro-optimizations are not terribly useful. If you shave off 1 second off a program that runs in 3 seconds, chances are nobody is even going to notice. Two seconds or three, who cares? Either way, it's too short to do anything else, and not long enough to matter. If you shave off an hour off a program that takes 20 hours, who is going to care? But so long as it doesn't introduce bugs, or make maintenance harder, or add complexity, such micro-optimizations don't harm either. HEY! That was MY argument! ;-)) Newsgroups: comp.lang.python Subject: Re: If/then style question Date: Tue, 21 Dec 2010 20:54:02 +0100 I'd bet you would stress your point Steven! But you don't need to persuade me, I do already agree. I just meant to say that, when the advantage is little, there's no need to rewrite a working function. And that with modern CPUs, if tests take so little time, that even some redundant one is not so much of a nuisance. in your working example, the payload is just a couple of integer calculations, that take very little time too. So the overhead due to redundant if tests does show clearly. And also in that not-really-real situation, 60% overhead just meant less than 3 seconds. Just for the sake of discussion, I tried to give both functions some plough to pull, and a worst-case situation too: t1 = Timer('for x in range(100): print func1(0),', ... 'from __main__ import func1') t2 = Timer('for x in range(100): print func2(0),', ... 'from __main__ import func2') min(t1.repeat(number=1, repeat=1)) -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 53.011015366479114 min(t2.repeat(number=1, repeat=1)) -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 47.55442856564332 that accounts for a scant 11% overhead, on more than one million tests per cycle. That said, let's make really clear that I would heartily prefer func2 to func1, based both on readability and speed. Thank you for having spent some time playing with me! Francesco On 19/12/2010 1.05, Steven D'Aprano wrote: Well, let's try it with a working (albeit contrived) example. This is just an example -- obviously I wouldn't write the function like this in real life, I'd use a while loop, but to illustrate the issue it will do. def func1(n): result = -1 done = False n = (n+1)//2 if n%2 == 1: result = n done = True if not done: n = (n+1)//2 if n%2 == 1: result = n done = True if not done: n = (n+1)//2 if n%2 == 1: result = n done = True if not done: for i in range(100): if not done: n = (n+1)//2 if n%2 == 1: result = n done = True return result def func2(n): n = (n+1)//2 if n%2 == 1: return n n = (n+1)//2 if n%2 == 1: return n n = (n+1)//2 if n%2
Re: while True or while 1
Steve Holden st...@holdenweb.com wrote in message news:mailman.462.1292214062.2649.python-l...@python.org... On 12/12/2010 2:32 PM, Christian Heimes wrote: Am 12.12.2010 19:31, schrieb Steve Holden: $ python -m timeit -n20 -- i = 0 while 1: i+=1 if i == 100: break 20 loops, best of 3: 89.7 msec per loop $ python -m timeit -n20 -- i = 0 while True: i+=1 if i == 100: break 20 loops, best of 3: 117 msec per loop No argue with that! I was merely making a point that while 1 executes different byte code than while True. Readability is important but sometimes speed is of the essence. while 1 is one of the few tricks to speed up tight loops a bit. OK, but the figures you quote save you 27.3 ms per million iterations, for a grand total saving of 27.3 ns per iteration. So a bit is hardly worth considering for most programs, is it? One these is 30% faster than the other. That's an appreciable difference, which you can't really just dismiss. And you can't tell what the overall effect on a program will be: perhaps the loop will be in a library function , which might be called billions of times. -- Bartc -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On 12/16/2010 5:44 AM, BartC wrote: On 12/12/2010 2:32 PM, Christian Heimes wrote: Am 12.12.2010 19:31, schrieb Steve Holden: $ python -m timeit -n20 -- i = 0 while 1: i+=1 if i == 100: break 20 loops, best of 3: 89.7 msec per loop $ python -m timeit -n20 -- i = 0 while True: i+=1 if i == 100: break 20 loops, best of 3: 117 msec per loop No argue with that! I was merely making a point that while 1 executes different byte code than while True. Readability is important but sometimes speed is of the essence. while 1 is one of the few tricks to speed up tight loops a bit. OK, but the figures you quote save you 27.3 ms per million iterations, for a grand total saving of 27.3 ns per iteration. So a bit is hardly worth considering for most programs, is it? One these is 30% faster than the other. That's an appreciable difference, which you can't really just dismiss. And you can't tell what the overall effect on a program will be: perhaps the loop will be in a library function , which might be called billions of times. It might. But if the code it is calling does *anything* at all significant I can promise you that spending an extra 30% purely on the looping construct will still make a negligible difference to a program's execution time, and there are almost certainly going to be many other aspects of performance that will yield greater benefits from tuning. I realise that there are going to be some people who just flatly say since 'while 1:' is quicker I am going to use it every time, and that their programs will still work. And I still maintain that (for English speakers) while True: is to be preferred. shol...@lifeboy ~ $ python -m timeit -- i = 1 while True: i += 1 if i == 100: break 10 loops, best of 3: 157 msec per loop shol...@lifeboy ~ $ python -m timeit -- i = 1 while True: i += 1 if i == 100: break x = i+1 10 loops, best of 3: 238 msec per loop shol...@lifeboy ~ $ python -m timeit -- i = 1 while 1: i += 1 if i == 100: break 10 loops, best of 3: 116 msec per loop shol...@lifeboy ~ $ python -m timeit -- i = 1 while 1: i += 1 if i == 100: break x = i+1 10 loops, best of 3: 195 msec per loop If binding a simple arithmetic expression adds more to the loop than the difference between while 1: and while True: you are wasting your time thinking about the savings under all but the most rigorous circumstances. Fortunately there is no penalty for ignoring my advice. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 PyCon 2011 Atlanta March 9-17 http://us.pycon.org/ See Python Video! http://python.mirocommunity.org/ Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
BartC wrote: Steve Holden st...@holdenweb.com wrote in message news:mailman.462.1292214062.2649.python-l...@python.org... On 12/12/2010 2:32 PM, Christian Heimes wrote: Am 12.12.2010 19:31, schrieb Steve Holden: $ python -m timeit -n20 -- i = 0 while 1: i+=1 if i == 100: break 20 loops, best of 3: 89.7 msec per loop $ python -m timeit -n20 -- i = 0 while True: i+=1 if i == 100: break 20 loops, best of 3: 117 msec per loop No argue with that! I was merely making a point that while 1 executes different byte code than while True. Readability is important but sometimes speed is of the essence. while 1 is one of the few tricks to speed up tight loops a bit. OK, but the figures you quote save you 27.3 ms per million iterations, for a grand total saving of 27.3 ns per iteration. So a bit is hardly worth considering for most programs, is it? One these is 30% faster than the other. That's an appreciable difference, which you can't really just dismiss. Anecdotal evidence says it is easily dismissed: I had a routine that processed records from a table using custom, on the fly, code. I could either use exec for each record to do the work, or create a function that would then be called. I timed exec vs function, and found the function style to be about 200% faster... Eureka!, I thought. After putting the functional method in place, a run that took about 16 minutes using the old exec method ran two (2!) seconds faster. Great learning experience, for both the function method (which I prefer), and the need for profiling. ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
Ethan Furman et...@stoneleaf.us writes: ...I timed exec vs function, and found the function style to be about 200% faster... So it finished before it started? -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On 12/16/2010 7:23 AM, Steve Holden wrote: On 12/16/2010 5:44 AM, BartC wrote: One these is 30% faster than the other. That's an appreciable difference, which you can't really just dismiss. And you can't tell what the overall effect on a program will be: perhaps the loop will be in a library function , which might be called billions of times. It might. But if the code it is calling does *anything* at all significant I can promise you that spending an extra 30% purely on the looping construct will still make a negligible difference to a program's execution time, and there are almost certainly going to be many other aspects of performance that will yield greater benefits from tuning. I realise that there are going to be some people who just flatly say since 'while 1:' is quicker I am going to use it every time, and that their programs will still work. And I still maintain that (for English speakers) while True: is to be preferred. shol...@lifeboy ~ $ python -m timeit -- i = 1 while True: i += 1 if i == 100: break 10 loops, best of 3: 157 msec per loop shol...@lifeboy ~ $ python -m timeit -- i = 1 while True: i += 1 if i == 100: break x = i+1 10 loops, best of 3: 238 msec per loop shol...@lifeboy ~ $ python -m timeit -- i = 1 while 1: i += 1 if i == 100: break 10 loops, best of 3: 116 msec per loop shol...@lifeboy ~ $ python -m timeit -- i = 1 while 1: i += 1 if i == 100: break x = i+1 10 loops, best of 3: 195 msec per loop This are all Python2 timings. If binding a simple arithmetic expression adds more to the loop than the difference between while 1: and while True: you are wasting your time thinking about the savings under all but the most rigorous circumstances. *Especially* when the 'problem' has been fixed in Python 3. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
Arnaud Delobelle wrote: Ethan Furman et...@stoneleaf.us writes: ...I timed exec vs function, and found the function style to be about 200% faster... So it finished before it started? Hmmm Let me check my calculator... . . . Ah! Okay, that was 200x faster. :) I think -- it was a few months ago now, and my numbers might be off a bit, but I was definitely impressed with A) how much faster the function style was, and B), how very little time it saved me. ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
Steve Holden st...@holdenweb.com wrote in message news:mailman.54.1292502247.6505.python-l...@python.org... On 12/16/2010 5:44 AM, BartC wrote: One these is 30% faster than the other. That's an appreciable difference, which you can't really just dismiss. shol...@lifeboy ~ $ python -m timeit -- i = 1 while True: i += 1 if i == 100: break 10 loops, best of 3: 157 msec per loop $ python -m timeit -- i = 1 while 1: i += 1 if i == 100: break 10 loops, best of 3: 116 msec per loop I used a single loop counting to 10 million, and the timings were roughly 2.5xx and 1.8xx seconds, on Python 2.5 (1.35 and 1.05 seconds inside a function). In terms of a more realistic function (admittedly still a little contrived, as the loop would be written differently), I tried this: def p2(n): p=1 while True: if n=p: return p p=1 return 0 for i in xrange(100): x=p2(i) p2() calculates the smallest power of 2 = it's operand. Using while True as shown, it took 3.4 seconds. Using While 1, it took 2.6 seconds (Python 2.5). -- Bartc -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On Dec 16, 4:34 pm, BartC b...@freeuk.com wrote: def p2(n): p=1 whileTrue: if n=p: return p p=1 return 0 for i in xrange(100): x=p2(i) p2() calculates the smallest power of 2 = it's operand. def p2(n): return 1 n.bit_length() -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On Thu, 16 Dec 2010 23:34:21 +, BartC wrote: In terms of a more realistic function (admittedly still a little contrived, as the loop would be written differently), I tried this: def p2(n): p=1 while True: if n=p: return p p=1 return 0 for i in xrange(100): x=p2(i) p2() calculates the smallest power of 2 = it's operand. Using while True as shown, it took 3.4 seconds. Using While 1, it took 2.6 seconds (Python 2.5). Right. And a saving of 0.8 microseconds per iteration is a micro- optimization which is likely to be invisible in any real situation. I mean, yes, you saved almost an entire second. Wow. Save another 179 of them and you'll almost have enough time to make yourself a coffee. Bart, we get it. Nobody denies that the optimization is real, only that it is generally meaningful. Who cares whether it takes 2 seconds or 4 seconds to generate one million results if the rest of the application takes 3 minutes to run? *If* your application is such that saving 0.8 microseconds per iteration actually is useful, AND your loop has to be written as a while True loop, then this *may* be a useful micro-optimization to save 0.8 microseconds per iteration. That's a vanishingly tiny proportion of all code written. If your code happens to meet those conditions, then by all means use while 1. Or move to Python 3, where while True has the same optimization performed. But in general, such micro-optimizations are not terribly useful. If you shave off 1 second off a program that runs in 3 seconds, chances are nobody is even going to notice. Two seconds or three, who cares? Either way, it's too short to do anything else, and not long enough to matter. If you shave off an hour off a program that takes 20 hours, who is going to care? But so long as it doesn't introduce bugs, or make maintenance harder, or add complexity, such micro-optimizations don't harm either. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On 14 déc, 21:38, Arnaud Delobelle arno...@gmail.com wrote: I almost used: True = to be or not to be # that is the question KEYBOARD !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On Tuesday 14 December 2010, 21:38:47 Arnaud Delobelle wrote: Christian Heimes li...@cheimes.de writes: [...] Tres Seavers once told me a joke like this: True = not not Who's at the door? # say it out loud! This was back in the old days of Zope 2.5 and Python 2.1, which didn't have True and False. I almost used: True = to be or not to be # that is the question That's wrong: to be or not to be 'to be' You need to wrap it with bool() at least (even without interpreting Pythons answer to the duality contradiction of consciousness for now ;-)) but didn't dare! Pete -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On 12/15/2010 8:10 AM, Hans-Peter Jansen wrote: On Tuesday 14 December 2010, 21:38:47 Arnaud Delobelle wrote: Christian Heimes li...@cheimes.de writes: [...] Tres Seavers once told me a joke like this: True = not not Who's at the door? # say it out loud! This was back in the old days of Zope 2.5 and Python 2.1, which didn't have True and False. I almost used: True = to be or not to be # that is the question That's wrong: to be or not to be 'to be' You need to wrap it with bool() at least (even without interpreting Pythons answer to the duality contradiction of consciousness for now ;-)) but didn't dare! Yeah, if Hamlet had been a Python programmer that play would have been a light comedy. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 PyCon 2011 Atlanta March 9-17 http://us.pycon.org/ See Python Video! http://python.mirocommunity.org/ Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
Steven D'Aprano wrote: while True: ... print Looping ... True = 0 Just remember that if you use that inside a function, you'll have to initialise True to True before... er, wait a moment, that won't work... ah, I know: def f(true = True): True = true while True: ... True = False -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On Tuesday 14 December 2010, 10:19:04 Gregory Ewing wrote: Steven D'Aprano wrote: while True: ... print Looping ... True = 0 Just remember that if you use that inside a function, you'll have to initialise True to True before... er, wait a moment, that won't work... ah, I know: def f(true = True): True = true while True: ... True = False Thankfully, with Python 3 this code falls flat on its face. If I would have to _consume_ code like that more often, it would require me to also use a vomit resistant keyboard cover.. Pete -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
Am 14.12.2010 11:33, schrieb Hans-Peter Jansen: On Tuesday 14 December 2010, 10:19:04 Gregory Ewing wrote: Steven D'Aprano wrote: while True: ... print Looping ... True = 0 Just remember that if you use that inside a function, you'll have to initialise True to True before... er, wait a moment, that won't work... ah, I know: def f(true = True): True = true while True: ... True = False Thankfully, with Python 3 this code falls flat on its face. If I would have to _consume_ code like that more often, it would require me to also use a vomit resistant keyboard cover.. Pete True yesterday, today and in the future: Yesterday: Pilate said to him, True? what is true? Having said this he went out again to the Jews and said to them, I see no wrong in him. Today: We are so thankful that today we are free to define True ourselves using Python 2.x. Future: Be warned, the future gets darker! ;-) Grüessli -- Kurt Mueller -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
Gregory Ewing greg.ew...@canterbury.ac.nz writes: Steven D'Aprano wrote: while True: ... print Looping ... True = 0 Just remember that if you use that inside a function, you'll have to initialise True to True before... er, wait a moment, that won't work... ah, I know: def f(true = True): True = true while True: ... True = False You also need to initialise False to False for it to be really robust. So something like this will do. True = not 0 False = not True while True: ... True = False :) -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
Am 14.12.2010 17:52, schrieb Arnaud Delobelle: You also need to initialise False to False for it to be really robust. So something like this will do. True = not 0 False = not True while True: ... True = False Tres Seavers once told me a joke like this: True = not not Who's at the door? # say it out loud! This was back in the old days of Zope 2.5 and Python 2.1, which didn't have True and False. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
Christian Heimes li...@cheimes.de writes: [...] Tres Seavers once told me a joke like this: True = not not Who's at the door? # say it out loud! This was back in the old days of Zope 2.5 and Python 2.1, which didn't have True and False. I almost used: True = to be or not to be # that is the question but didn't dare! -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
Paul Rubin wrote: Steven D'Aprano steve+comp.lang.pyt...@pearwood.info writes: I'm actually quite fond of the look of while 1:, and sometimes use it, not because it's faster, but just because I like it. for v in itertools.repeat(True): ... ;-) while '__For_ever___' not in ['nit-picking']: :) JM -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On 2010-12-12, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: With the while True idiom in Python 2.x, you can easily exit out of an infinite loop without using break: while True: ... print Looping ... True = 0 ... Looping while True: # Execute an infinite loop in 0 seconds. ... print Looping ... *wink* Sadly, I've seen people do stuff like that in real programs... -- Grant Edwards grant.b.edwardsYow! I was making donuts at and now I'm on a bus! gmail.com -- http://mail.python.org/mailman/listinfo/python-list
while True or while 1
I'm sure this has been brought up many times, but a quick Googling didn't yield the decisive results I was hoping for, so I apologize if this has already been addressed in great detail somewhere else. I am wondering what the rationale is behind preferring while True over while 1? For me, it seems that using True provides more clarity, but is that the only benefit? Is while 1 more prone to errors? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
Am 12.12.2010 15:14, schrieb Max Countryman: I'm sure this has been brought up many times, but a quick Googling didn't yield the decisive results I was hoping for, so I apologize if this has already been addressed in great detail somewhere else. I am wondering what the rationale is behind preferring while True over while 1? For me, it seems that using True provides more clarity, but is that the only benefit? Is while 1 more prone to errors? In Python 2.x, while 1 is slightly faster than while True. The interpreter can't optimize while True because the name True can be bind to another value. In Python 3.x it's no longer possible to rebind the names True and False just like None in Python 2.x Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On Sun, Dec 12, 2010 at 3:14 PM, Max Countryman m...@me.com wrote: I'm sure this has been brought up many times, but a quick Googling didn't yield the decisive results I was hoping for, so I apologize if this has already been addressed in great detail somewhere else. I am wondering what the rationale is behind preferring while True over while 1? For me, it seems that using True provides more clarity, but is that the only benefit? Is while 1 more prone to errors? It's just silly to use 1 since it will evaluate to True either way. -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On 12/12/2010 10:30 AM, Christian Heimes wrote: Am 12.12.2010 15:14, schrieb Max Countryman: I'm sure this has been brought up many times, but a quick Googling didn't yield the decisive results I was hoping for, so I apologize if this has already been addressed in great detail somewhere else. I am wondering what the rationale is behind preferring while True over while 1? For me, it seems that using True provides more clarity, but is that the only benefit? Is while 1 more prone to errors? In Python 2.x, while 1 is slightly faster than while True. The interpreter can't optimize while True because the name True can be bind to another value. In Python 3.x it's no longer possible to rebind the names True and False just like None in Python 2.x Would you care to quantify how much CPU time that optimization will typically save for a loop of fair magnitude (say, a billion iterations)? Python is designed to provide readable code. Writing while True: ... is much more legible than its pre-True couterpart while 1: ... and is, I'd say, therefore to be preferred (except in a code base intended to compile on 2.2 and before). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 PyCon 2011 Atlanta March 9-17 http://us.pycon.org/ See Python Video! http://python.mirocommunity.org/ Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
Am 12.12.2010 19:31, schrieb Steve Holden: Would you care to quantify how much CPU time that optimization will typically save for a loop of fair magnitude (say, a billion iterations)? The difference is minimal but measurable for very tight loops. $ python -m timeit -n20 -- i = 0 while 1: i+=1 if i == 100: break 20 loops, best of 3: 89.7 msec per loop $ python -m timeit -n20 -- i = 0 while True: i+=1 if i == 100: break 20 loops, best of 3: 117 msec per loop In Python 2.x the peep hole optimizer can't remove the global lookup and check for trueness for while True. def while1(): ... while 1: ... pass ... import dis dis.dis(while1) 2 0 SETUP_LOOP 3 (to 6) 3 3 JUMP_ABSOLUTE3 6 LOAD_CONST 0 (None) 9 RETURN_VALUE def whiletrue(): ... while True: ... pass ... dis.dis(whiletrue) 2 0 SETUP_LOOP 12 (to 15) 3 LOAD_GLOBAL 0 (True) 6 JUMP_IF_FALSE4 (to 13) 9 POP_TOP 3 10 JUMP_ABSOLUTE3 13 POP_TOP 14 POP_BLOCK 15 LOAD_CONST 0 (None) 18 RETURN_VALUE Python is designed to provide readable code. Writing while True: ... is much more legible than its pre-True couterpart while 1: ... No argue with that! I was merely making a point that while 1 executes different byte code than while True. Readability is important but sometimes speed is of the essence. while 1 is one of the few tricks to speed up tight loops a bit. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
Python is designed to provide readable code. Writing while True: ... is much more legible than its pre-True couterpart while 1: ... No argue with that! I actually want to argue with that: I find while 1 more legible. That's probably because a) I'm use to it, and b) the English words while and True don't mean much to me, I need recognize them, and recognizing True is slightly more difficult than recognizing 1. In the end, in any project, there should be coding conventions, and authors should follow them. What is legible is IMO much more determined by convention than intuition, at least to experienced programmers (i.e. those that have been following the convention for a long time). Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On Sun, 12 Dec 2010 16:33:41 +0100, Krister Svanlund wrote: On Sun, Dec 12, 2010 at 3:14 PM, Max Countryman m...@me.com wrote: I'm sure this has been brought up many times, but a quick Googling didn't yield the decisive results I was hoping for, so I apologize if this has already been addressed in great detail somewhere else. I am wondering what the rationale is behind preferring while True over while 1? For me, it seems that using True provides more clarity, but is that the only benefit? Is while 1 more prone to errors? It's just silly to use 1 since it will evaluate to True either way. With the while True idiom in Python 2.x, you can easily exit out of an infinite loop without using break: while True: ... print Looping ... True = 0 ... Looping while True: # Execute an infinite loop in 0 seconds. ... print Looping ... *wink* -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On 12/12/2010 2:32 PM, Christian Heimes wrote: Am 12.12.2010 19:31, schrieb Steve Holden: Would you care to quantify how much CPU time that optimization will typically save for a loop of fair magnitude (say, a billion iterations)? The difference is minimal but measurable for very tight loops. $ python -m timeit -n20 -- i = 0 while 1: i+=1 if i == 100: break 20 loops, best of 3: 89.7 msec per loop $ python -m timeit -n20 -- i = 0 while True: i+=1 if i == 100: break 20 loops, best of 3: 117 msec per loop In Python 2.x the peep hole optimizer can't remove the global lookup and check for trueness for while True. Yes, you said that already and I certainly didn't disagree. [...] Python is designed to provide readable code. Writing while True: ... is much more legible than its pre-True couterpart while 1: ... No argue with that! I was merely making a point that while 1 executes different byte code than while True. Readability is important but sometimes speed is of the essence. while 1 is one of the few tricks to speed up tight loops a bit. OK, but the figures you quote save you 27.3 ms per million iterations, for a grand total saving of 27.3 ns per iteration. So a bit is hardly worth considering for most programs, is it? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 PyCon 2011 Atlanta March 9-17 http://us.pycon.org/ See Python Video! http://python.mirocommunity.org/ Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On Sun, 12 Dec 2010 23:20:40 -0500, Steve Holden wrote: On 12/12/2010 2:32 PM, Christian Heimes wrote: [...] No argue with that! I was merely making a point that while 1 executes different byte code than while True. Readability is important but sometimes speed is of the essence. while 1 is one of the few tricks to speed up tight loops a bit. OK, but the figures you quote save you 27.3 ms per million iterations, for a grand total saving of 27.3 ns per iteration. So a bit is hardly worth considering for most programs, is it? I don't think anyone is saying that people should routinely use while 1 for loops because they're faster than the alternatives. But it is a real, if small, optimization for a particular class of tight loops. Using the figures shown by Christian, it could be a 20-25% speed up on extremely tight loops. You're right though, it's hardly worth the effort for large, expensive loops though -- but then on the other hand, while 1 is not so unreadable that it should be avoided. I'm actually quite fond of the look of while 1:, and sometimes use it, not because it's faster, but just because I like it. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info writes: I'm actually quite fond of the look of while 1:, and sometimes use it, not because it's faster, but just because I like it. for v in itertools.repeat(True): ... ;-) -- http://mail.python.org/mailman/listinfo/python-list