432,403 Members | 880 Online
Need help? Post your question and get tips & solutions from a community of 432,403 IT Pros & Developers. It's quick & easy.

# Execution speed question

 P: n/a I am performing simulations on networks (graphs). I have a question on speed of execution (assuming very ample memory for now). I simplify the details of my simulation below, as the question I ask applies more generally than my specific case. I would greatly appreciate general feedback in terms of computing and of course considerations specific to implementation in Python. The nodes in my network may be ON or OFF. The network starts off with all nodes in the OFF state. I loop through the nodes. For each node that is OFF, I consider some probability of it turning ON based on the states of its neighbours. I MUST GO THROUGH ALL NODES BEFORE DECIDING WHICH ONES TO TURN ON. So my question is whether it is faster to 1. loop through a list of ALL nodes and check for OFF nodes using ifs or to 2. loop through a container of OFF nodes and remove from this when they turn ON The second would result in looping through less nodes, especially as the simulation progresses, but how does the cost of removal compare with cheap ifs and would the extra memory usage affect performance. I an appreciate that the cost of the if check, the number of nodes, and the type of container I use will come into the answer. In my case, the ifs are cheap boolean queries (whether the node is ON or OFF). The number of nodes is very large: millions for sure, maybe tens of millions. If considering (2), take note of my BOLD text above, which means I can't remove nodes as I iterate through them in the main loop. I naturally started coding with (2), but couldn't decide on the best data structure for python. A set seemed ideal for speedy removal, but then I can't iterate through them with out popping. An ordered list? Some creative solution with numpy arrays? There is also the complication that since we are in interpreted python, what is theoretically the best data structure may not in reality be optimal unless it is a default system object or coded externally in a compiled module. Of course, I will start experimenting to see what the execution difference is, but I would appreciate some suggestions from others re which is best and also on best data structure for (2). I'm not a newbie, so you can get technical with me python-wise and algorithm wise. I realise it is a 'basic' question, but it is something that I have always wondered about (cheap ifs versus extra structure) and with the number of nodes I am considering, it actually becomes an issue. Many Thanks, Suresh Jul 25 '08 #1
17 Replies

 P: n/a On Jul 25, 7:57*pm, Suresh Pillai >import randomclass Node: ... def __init__(self): ... self.on = False ... def toggle(self): ... self.on = random.choice([True, False]) ... >>nodes = [Node() for i in range(0, 10000)]for node in nodes: ... node.toggle() ... >>off_nodes = filter(lambda x: not x.on, nodes)len(off_nodes) 5050 Jul 25 '08 #2

 P: n/a I'd recommend using 'filter' and list comprehensions. Look at using reduce(). You can collect information about all of the nodes without necessarily building a large, intermediate list in the process. You might get some ideas from here [http://en.wikipedia.org/wiki/ Antiobjects]. Jul 25 '08 #3

 P: n/a On Jul 25, 10:57 am, Suresh Pillai

 P: n/a On Jul 25, 1:46 pm, Iain King

 P: n/a On Jul 25, 9:54*pm, Jeff

 P: n/a That's a good comparison for the general question I posed. Thanks. Although I do believe lists are less than ideal here and a different data structure should be used. To be more specific to my case: As mentioned in my original post, I also have the specific condition that one does not know which nodes to turn ON until after all the probabilities are calculated (lets say we take the top m for example). In this case, the second and third will perform worse as the second one will require a remove from the list after the fact and the third will require another loop through the nodes to build the new list. Jul 25 '08 #7

 P: n/a Iain King wrote: I think (2)'s poor performance is being amplified by how python handles lists and list deletions; the effect may be stymied in other languages Delete is O(n) (or "O(n/2) on average", if you prefer), while append is amortized O(1). Unless I'm missing something, your example keeps going until it's flagged *all* nodes as "on", which, obviously, kills performance for the first version as the probability goes down. The OP's question was about a single pass (but he did mention "as the simulation progresses", so I guess it's fair to test a complete simulation.) Btw, if the nodes can be enumerated, I'd probably do something like: node_list = ... get list of nodes ... random.shuffle(node_list) start = 0 end = len(node_list) step = end / MAX while start < end: for i in xrange(start, start + step): ... switch on node_list[i] ... ... do whatever you want to do after a step ... # prepare for next simulation step start += step step = max((len(node_list) - start) / MAX, 1) which is near O(n) overall, and mostly constant wrt. the probability for each pass (where the probability is 1:MAX). Might need some tuning; tweak as necessary. Jul 25 '08 #8

 P: n/a On Fri, 25 Jul 2008 16:51:42 +0200, Fredrik Lundh wrote: Unless I'm missing something, your example keeps going until it's flagged *all* nodes as "on", which, obviously, kills performance for the first version as the probability goes down. The OP's question was about a single pass (but he did mention "as the simulation progresses", so I guess it's fair to test a complete simulation.) I was referring to multiple passes as in Iain' test cases. Although not necessarily till all nodes are ON, let's say to to a large proportion at least. Jul 25 '08 #9

 P: n/a On Jul 25, 3:39 pm, Suresh Pillai

 P: n/a Suresh Pillai wrote: That's a good comparison for the general question I posed. Thanks. Although I do believe lists are less than ideal here and a different data structure should be used. To be more specific to my case: As mentioned in my original post, I also have the specific condition that one does not know which nodes to turn ON until after all the probabilities are calculated (lets say we take the top m for example). In this case, the second and third will perform worse as the second one will require a remove from the list after the fact and the third will require another loop through the nodes to build the new list. -- http://mail.python.org/mailman/listinfo/python-list It seems like the probability calculation applies to all three equally, and can therefore be ignored for the simulations. You said that your algorithm must be a two-stage process: (A) calculate the probabilities then (B) turn on some nodes. Iain's simulations assume (A) is already done. He just addressed the performance of (B). Part (A) is invariant for all his simulations, because your requirement forces it to be. As for different data structures, it largely depends on how you need to access the data. If you don't need to index the data, just loop through it, you might try a linked list. The performance hit in (2) is coming from the list del; using a linked list would make the removal constant rather than O(n), and may even execute faster than (3) as well. -Matt Jul 25 '08 #11

 P: n/a On Jul 25, 4:22 pm, Matthew Fitzgibbons

 P: n/a Iain King wrote: On Jul 25, 4:22 pm, Matthew Fitzgibbons It seems like the probability calculation applies to all three equally,and can therefore be ignored for the simulations. The probability affects (1) more. My reasoning for this being: as probability gets lower the number of times you have to loop over the list increases. (1) always loops over the full list, but with each successive iteration (2) and (3) are looping over smaller and smaller lists. In the end this adds up, with (1) becoming slower than (2), even though it starts out quicker. Iain -- http://mail.python.org/mailman/listinfo/python-list I meant the _calculation_ of the probability affects all three equally, not the value itself. As your simulations show, different probabilities affect the algorithms differently; I'm talking about the algorithm to arrive at the probability value. -Matt Jul 25 '08 #13

 P: n/a The number of nodes is very large: millions for sure, maybe tens of millions. If considering (2), take note of my BOLD text above, which means I can't remove nodes as I iterate through them in the main loop. Since your use of 'node' is pretty vague and I don't have a good sense of what tests you are running and how long they would take, I'm only speculating, but a single loop might be the wrong way to go about that. If you are going to be frequently running tests and switching nodes on/off, have you considered a separate set of processes to do both? For example: A set of some number of "tester" threads, that loop through and test, recording thier results (somewhere). You could then have a separate loop that runs every so often, checks all the current test values, and runs through the nodes once, switching them on or off. I know it's not exactly what you asked, but depending on what your nodes are exactly, you can avoid a lot of other problems down the road. What if your single loop dies or gets hung on a test? With a separate approach, you'll have a lot more resilience too.. if there's some problem with a single tester or node, it won't keep the rest of the program from continuing to function. Jul 26 '08 #14

 P: n/a On Fri, 25 Jul 2008 08:08:57 -0700, Iain King wrote: On Jul 25, 3:39 pm, Suresh Pillai That's a good comparison for the general question I posed. Thanks.Although I do believe lists are less than ideal here and a differentdata structure should be used.To be more specific to my case:As mentioned in my original post, I also have the specific conditionthat one does not know which nodes to turn ON until after all theprobabilities are calculated (lets say we take the top m for example).In this case, the second and third will perform worse as the second onewill require a remove from the list after the fact and the third willrequire another loop through the nodes to build the new list. So you need to loops through twice regardless? i.e. loop once to gather data on off nodes, do some calculation to work out what to turn on, then loop again to turn on the relevant nodes? If so, then I think the functions above remain the same, becoming the 2nd loop. Every iteration you do a first loop over the off_nodes (or them all for (1)) to gather the data on them, perform your calculation, and then perform one of the above functions (minus the setup code at the begining; basically starting at the 'for') as a second loop, with the goes_on function now returning a value based on the calculation (rather than the calculation itself as I had it). Performance should be similar. Iain If do I settle on an explicit loop to remove the nodes turned ON, then I realised this weekend that I could do this in the next iteration of the simulation (first loop above) and save some iteration overhead (the if checking will still be there of course). And thanks for pointing out that constructing a new list, for long lists, is faster than simple removal. It's obvious but I never really thought of it; good tip. Jul 28 '08 #15

 P: n/a On Fri, 25 Jul 2008 09:22:06 -0600, Matthew Fitzgibbons wrote: As for different data structures, it largely depends on how you need to access the data. If you don't need to index the data, just loop through it, you might try a linked list. The performance hit in (2) is coming from the list del; using a linked list would make the removal constant rather than O(n), and may even execute faster than (3) as well. -Matt Yes, this was my first inclination. So my question, as alluded to in my original post, is whether there are C compiled modules for linked lists, doubly linked lists, ordered lists ... (the standard data structures) somewhere, to get the extra performance out of them. With python we have all built up creative ways of using the native structures for efficiency reasons. This project was the first time (due to its extreme use of resources) that I've had to worry about these minute considerations of native vs new structure but also take into account native vs python level construct vs compiled module. [P.S. The linked list does compare well with (3) as expected.] Jul 28 '08 #16

 P: n/a Suresh Pillai

 P: n/a On Mon, 28 Jul 2008 15:04:43 +0200, Suresh Pillai wrote: I could of course use the old trick of using a dictionary with 'None' values and then using iterkeys(). But I thought sets were supposed to replace this. So maybe I should be asking a more basic question: is there any way to iterate over the items in a set other than converting to a list or using the pop() method. Yes, just do it. >>for i in set([1,2,3]): .... print i .... 1 2 3 -- Steven Jul 28 '08 #18

### This discussion thread is closed

Replies have been disabled for this discussion.