阿里巴巴面试题-超时装饰器

//评测题目: 实现一个decorator
//超时装饰器
//该decorator可以接收一个参数 `max_time` ,
//在decorator里面统计函数的执行时间,
//对于执行
时间超过 max_time 的函数打印出这个函数的名字

 

# -*- coding: utf-8 -*-

import signal
import time
max_time = 4

def set_timeout(num, callback):
    def wrap(func):
        def handle(signum, frame):
            raise RuntimeError

        def to_do(*args, **kwargs):
            try:
                signal.signal(signal.SIGALRM, handle)  # 设置信号和回调函数
                signal.alarm(num)
                print('start alarm signal.')
                r = func(*args, **kwargs)
                print('close alarm signal.')
                signal.alarm(0)
                return r
            except RuntimeError as e:
                callback(func)

        return to_do

    return wrap


def after_timeout(func):
    print "{} Time out!".format(func.__name__)


@set_timeout(max_time, after_timeout)  #
def connect():
    time.sleep(3)
    print('Finished without timeout.')


if __name__ == '__main__':
    connect()

 

你可能感兴趣的:(python基础,面试题)