Re: Timed execution in eval



2008/3/7, Steven D'Aprano <steve@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx>:
On Fri, 07 Mar 2008 08:12:38 -0800, alex.pedwysocki wrote:

> I have various bits of code I want to interpret and run at runtime in
> eval ...


I hope that code doesn't contain any data coming from an untrusted user.



> I want to be able to detect if they fail with error,


That's what try...except blocks are for.

try:
x = eval('1 + 1 = 2')
except SyntaxError:
x = 3



> I want to be able to time them,


That's what the timeit module is for.

If you do time them, you will find that eval(expr) is MUCH MUCH slower
than just executing expr as normal.

>>> from timeit import Timer
>>> Timer('1+1').timeit()
0.25557518005371094
>>> Timer('eval("1+1")').timeit()
21.816912174224854

If you use eval() a lot, you will have a SLOW program.



> and I want to be able to stop them if they run too long.


That's tricky. As far as I know, the only way for a Python program to
stop an arbitrary calculation after a certain period of time it to run it
in a thread. You then monitor the elapsed time, and when the timer
expires, ask the thread to die. And hope it listens.


Or you could use setitimer (not available for now). I opened an issue
at roundup to add setitimer and getitimer wrappers to the signal
module.
It would be great if you could test on your platform. It was done for
py3k, but could easily be back ported to python 2.6.

http://bugs.python.org/issue2240



> I cannot add code to the eval'd strings that will help me accomplish
> this.


You can't? Why ever not?

Note: that's almost certainly the wrong way to solve your problem, but
I'm curious as to why you can't.



--

Steven

--
http://mail.python.org/mailman/listinfo/python-list



--
-- Guilherme H. Polo Goncalves
.



Relevant Pages

  • Re: posix-cpu-timers revamp
    ... Tests with a process CPU timer set for a long expiration time. ... interval as set by setitimer. ... the first time it fires at the value set by setitimerbut from then on ... The current value of an itimer is a user feature, ...
    (Linux-Kernel)
  • Re: posix-cpu-timers revamp
    ... analogous cache of the soonest timer to expire, ... the setitimer settings for ITIMER_. ... the expiration time as set by setitimer, but after the timer fires the ... the first time it fires at the value set by setitimerbut from then on ...
    (Linux-Kernel)
  • Re: One-shot timer in Linux
    ... <Nortem Lazarok> ... man 2 setitimer ... man 2 nanosleep ... How you implement it depends on whether you want the timer to be ...
    (comp.os.linux.development.apps)
  • Re: is there any timer function in linux ?
    ... > The trouble is, it only lets you set one timer at a time. ... > There seems to be no direct equivalent to the $SETIMR/$CANTIM services ... Setitimer can setup only one timer per application. ...
    (comp.os.linux.development.apps)