-3

I wrote a python program that generates random mathematical strings, such as "2+3**4/3" and "3**3**50-2", and then uses eval() to compute them.

Computing "2+3**4/3" will work fine but evaluating "3**3**50-2" will take too long since it will be a very large number. I need to check if the power will be too large to compute before it tries, or I need to terminate the function after a certain amount of time.

Since this function needs to be run tens of thousands of times, efficiency is very important

I've tried using the "multiprocessing" and "threading" libraries to terminate the thread if it takes over a second, but these solutions slow down the program too much.

Any suggestions? I'm completely stumped on this one. Thanks.

Titan
  • 33
  • 10
  • 2
    Does a system of timeout would fit ? Like you allow 10sec of computing and if it tkes more it stops ? – azro Nov 19 '20 at 19:00
  • @azro That seems like a good solution, how would I go about doing that? – Titan Nov 19 '20 at 19:03
  • Does this answer your question? [Timeout on a function call](https://stackoverflow.com/questions/492519/timeout-on-a-function-call) – mkrieger1 Nov 19 '20 at 19:05
  • I tried using multiprocessing (since I'm on windows) and multiprocessing.Manager() (so I can return things from the function) and it works, the only problem is it seems to be very inefficient. It takes about an extra second to time one function, and before I could run the function about 4000 times per second. Is this normal or did I implement something wrong? – Titan Nov 19 '20 at 19:50

1 Answers1

0

I found a fast and simple solution to this problem:

try:
    eval("math.pow(a,b)")
except:
    print("too long to compute")

Instead of using ** I used math.pow so it returns an overflow error if 'a' and 'b' are too large. Then the exception can be handled with a try-except statement.

Titan
  • 33
  • 10