0

I'm calling a function A(i) in python . I want it to be terminated if it executes for more than X milliseconds. I've looked at some ways of timing out including signal.alarm(), but they all take the time in integral seconds. I want to do something like:

signal.alarm(0.26) //time out after 0.26 seconds

How do I do this?

mjsxbo
  • 2,116
  • 3
  • 22
  • 34
  • 3
    Possible duplicate of [Python - signal.alarm function](https://stackoverflow.com/questions/3770711/python-signal-alarm-function) – Galen Dec 21 '17 at 08:48
  • Did you try the signal function? – user1767754 Dec 21 '17 at 08:49
  • 1
    The title of that linked duplicate is a little misleading. Try using [`signal.setitimer`](https://docs.python.org/3/library/signal.html#signal.setitimer), which accepts a float. – Galen Dec 21 '17 at 08:51
  • Possible duplicate of [Timeout function if it takes too long to finish](https://stackoverflow.com/questions/2281850/timeout-function-if-it-takes-too-long-to-finish) – user1767754 Dec 21 '17 at 08:54

2 Answers2

0

Aside from the solution I linked as a possible duplicate, you could also use ctypes to use ualarm if your system supports it.

For example, on macOS:

import ctypes

libc = ctypes.CDLL("libc.dylib")

libc.ualarm(10000, 0) # 10,000 microseconds
Galen
  • 1,307
  • 8
  • 15
-2

singal.settimer requires unix. Else you can use time.time()

import time

start = time.time()
now = time.time()
while now - start < 0.26: # 0.26 seconds
   now = time.time()
print (now-start)

you can use a decorator, put your function under the while loop or raise an exception when timer ends (and probably others).

You may have to thread the timer.

Gsk
  • 2,929
  • 5
  • 22
  • 29