deftime_sleep(): for i inrange(10): print i time.sleep(1) # delay 1s, not that accurate
if __name__ == "__main__": start = time.time() time_sleep() end = time.time() print"run time: {}".format(end - start)
time.time 单线程非阻塞延时/超时
通过比较时间戳实现, 多用于循环中的延时/超时判断
import time
deftime_compare(): timeout = time.time() + 10# 10s delay for i inrange(20): print i time.sleep(1) if timeout < time.time(): # compare the timestamps break print"time out !"
if __name__ == "__main__": start = time.time() time_compare() end = time.time() print"run time: {}".format(end - start)
defstart(self): """Start the thread.""" self.__run_backup = self.run # Force the Thread to install our trace. self.run = self.__run threading.Thread.start(self)
def__run(self): """Hacked run function, which installs the trace.""" sys.settrace(self.globaltrace) self.__run_backup() self.run = self.__run_backup
"""Wrap the original function.""" deffunc_wrapper(*args, **kwargs): result = [] # create new args for _new_func, because we want to get the func # return val to result list new_kwargs = { 'oldfunc': func, 'result': result, 'oldfunc_args': args, 'oldfunc_kwargs': kwargs }
defstart(self): """Start the thread.""" self.__run_backup = self.run # Force the Thread to install our trace. self.run = self.__run threading.Thread.start(self)
def__run(self): """Hacked run function, which installs the trace.""" sys.settrace(self.globaltrace) self.__run_backup() self.run = self.__run_backup
result = [] kwargs = {} if kwargs isNoneelse kwargs # create new args for _new_func, because we want to get the func # return val to result list new_kwargs = { 'oldfunc': func, 'result': result, 'oldfunc_args': args, 'oldfunc_kwargs': kwargs }
deftimeout(s): ''' use as decorator to exit process if function takes longer than s seconds ''' defouter(fn): definner(*args, **kwargs): timer = threading.Timer(s, timeout_quit, args=[fn.__name__]) timer.start() try: result = fn(*args, **kwargs) finally: timer.cancel() return result return inner return outer
if __name__ == "__main__": import time
@timeout(5) defprocessNum(num): time.sleep(2) return num
# If thread is still active if prcs.is_alive(): print"main process: kill" prcs.terminate() prcs.join() print"main process: end"
defprocessing_sub(name): for i inrange(100): # if use print, can not show immediately in the console. logging.error("{}: {}".format(name, i)) time.sleep(1)
if __name__ == "__main__": start = time.time() processing_main() end = time.time() print"run time: {}".format(end - start)
deftimeout(timeout, default=None, try_except=False): """Timeout decorator, parameter in seconds.""" deftimeout_decorator(item): """Wrap the original function.""" @functools.wraps(item) deffunc_wrapper(*args, **kwargs): """Closure for function.""" pool = multiprocessing.pool.ThreadPool(processes=1) # pool = multiprocessing.pool.Pool(processes=1) ## raise error about pickle problem!!! try: async_result = pool.apply_async(item, args, kwargs) val = async_result.get(timeout) except multiprocessing.TimeoutError: pool.terminate() ## not work here, because it is acutally thread, not process!!! val = default if try_except isTrue: raise multiprocessing.TimeoutError else: pool.close() pool.join() return val return func_wrapper return timeout_decorator
if __name__ == "__main__": import time
@timeout(5) defcount(name): for i inrange(10): print("{}: {}".format(name, i)) time.sleep(1) return"finished"
start = time.time() print count("thread1") print count("thread2") ## you can find problem here, thread1 is still running... end = time.time() print"run time: {}".format(end - start)
import multiprocessing
deftimeout_call(timeout, func, args=(), kwargs=None, default=None, try_except=False): kwargs = {} if kwargs isNoneelse kwargs pool = multiprocessing.Pool(processes=1) try: async_result = pool.apply_async(func, args, kwargs) val = async_result.get(timeout) except multiprocessing.TimeoutError: pool.terminate() val = default if try_except isTrue: raise multiprocessing.TimeoutError else: pool.close() pool.join() return val
################### example ########## import logging import time
defcount(name): for i inrange(10): logging.error("{}: {}".format(name, i)) time.sleep(1) return"finished"
if __name__ == "__main__": ## if count function is here, will raise error!!!