1717import collections
1818import concurrent .futures
1919import heapq
20+ import inspect
2021import logging
2122import socket
2223import subprocess
3738_MAX_WORKERS = 5
3839
3940
41+ def _format_handle (handle ):
42+ cb = handle ._callback
43+ if inspect .ismethod (cb ) and isinstance (cb .__self__ , tasks .Task ):
44+ # format the task
45+ return repr (cb .__self__ )
46+ else :
47+ return str (handle )
48+
49+
4050class _StopError (BaseException ):
4151 """Raised to stop the event loop."""
4252
@@ -128,6 +138,9 @@ def __init__(self):
128138 self ._clock_resolution = time .get_clock_info ('monotonic' ).resolution
129139 self ._exception_handler = None
130140 self ._debug = False
141+ # In debug mode, if the execution of a callback or a step of a task
142+ # exceed this duration in seconds, the slow callback/task is logged.
143+ self .slow_callback_duration = 0.1
131144
132145 def __repr__ (self ):
133146 return ('<%s running=%s closed=%s debug=%s>'
@@ -823,16 +836,16 @@ def _run_once(self):
823836 if logger .isEnabledFor (logging .INFO ):
824837 t0 = self .time ()
825838 event_list = self ._selector .select (timeout )
826- t1 = self .time ()
827- if t1 - t0 >= 1 :
839+ dt = self .time () - t0
840+ if dt >= 1 :
828841 level = logging .INFO
829842 else :
830843 level = logging .DEBUG
831844 if timeout is not None :
832845 logger .log (level , 'poll %.3f took %.3f seconds' ,
833- timeout , t1 - t0 )
846+ timeout , dt )
834847 else :
835- logger .log (level , 'poll took %.3f seconds' , t1 - t0 )
848+ logger .log (level , 'poll took %.3f seconds' , dt )
836849 else :
837850 event_list = self ._selector .select (timeout )
838851 self ._process_events (event_list )
@@ -855,7 +868,16 @@ def _run_once(self):
855868 ntodo = len (self ._ready )
856869 for i in range (ntodo ):
857870 handle = self ._ready .popleft ()
858- if not handle ._cancelled :
871+ if handle ._cancelled :
872+ continue
873+ if self ._debug :
874+ t0 = self .time ()
875+ handle ._run ()
876+ dt = self .time () - t0
877+ if dt >= self .slow_callback_duration :
878+ logger .warning ('Executing %s took %.3f seconds' ,
879+ _format_handle (handle ), dt )
880+ else :
859881 handle ._run ()
860882 handle = None # Needed to break cycles when an exception occurs.
861883
0 commit comments