I've been making a genetic program and I've come across a problem. It seems that it will try to calculate large exponents but freeze (which is understandable, because it is a large number) in the process. Is there any way to time the execution? This way I could stop calculating before it freezes for several minutes. Thank you for your help!
Asked
Active
Viewed 235 times
0
-
1I have a great idea: Don't use `eval`!! – aIKid Nov 11 '13 at 23:44
-
1use [Threads](http://www.ibm.com/developerworks/aix/library/au-threadingpython/) for heavy computational work. – clcto Nov 11 '13 at 23:44
-
`eval` is bad stuff.. Also, you need to show us some code to find what's wrong with it. – aIKid Nov 11 '13 at 23:44
-
1@clcto: No, not in Python, especially CPython. In CPython, if you have more than one CPU-bound thread, they just get in each other's way. (And before 3.2, even having _one_ CPU-bound thread gets in the way of other threads.) So you should use _processes_ for heavy computational work, not threads. (And it's often not a bad idea in other languages; it avoids many of the painful race problems that plague multithreaded programs.) – abarnert Nov 11 '13 at 23:50
-
What should function or process I use instead of eval() and multiprocessing for calculating the value of strings while timing them to make sure they don't take hours? An example would be eval("85*85940385034"). – user2514631 Nov 12 '13 at 23:40
1 Answers
0
Generally, you don't really want to do what you're asking. (In fact, there's more than one red flag there.) But if you do:
The only way you can let something run, while also timing is, is to put it in a separate thread or process.
If you want to be able to forcibly interrupt that something, it has to be a process.
So, for example:
import multiprocessing
def try_slow_thing(function, args, timeout):
p = multiprocessing.Process(target=function, args=args)
p.start()
p.join(timeout)
if p.is_alive():
p.terminate()
raise TimeoutError("stupid process wouldn't finish")
If you want to return a value from the function, or share values from the main process, or anything else more fancy than just "run and finish or don't", read the introductory parts of the multiprocessing
docs and skim the rest. (In fact, do that anyway.)

abarnert
- 354,177
- 51
- 601
- 671