装饰器给Python函数调用增加了多少开销 [英] How much overhead do decorators add to Python function calls

查看:96
本文介绍了装饰器给Python函数调用增加了多少开销的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在为我的塔架应用程序使用定时装饰器,以提供特定功能的实时定时信息。我是通过创建装饰器&只需将其附加到我想定时的控制器中的任何函数上即可。

I've been playing around with a timing decorator for my pylons app to provide on the fly timing info for specific functions. I've done this by creating a decorator & simply attaching it to any function in the controller I want timed.

不过,有人指出,装饰器可能会给调用增加相当大的开销,并且它们会运行比未修饰的函数慢2-3倍。

It's been pointed out however that decorators could add a fair amount of overhead to the call, and that they run 2-3x slower than an undecorated function.

首先,我希望执行修饰后的函数所需的时间比未修饰的函数要长,但我希望这样做的开销达到千分之一秒与SQL插入调用相比,可以忽略不计。装饰器本身使用time.time()&一些非常简单的聚合。

Firstly, I would expect that executing a decorated function would take a smite longer than an undecorated one, but I would expect that overhead to be in the thousandths of seconds & be negligible compared to a SQL insert call. The decorator itself does simple simple timing calculations using time.time() & some very simple aggregation.

装饰器会增加系统的大量开销吗?我找不到任何支持的东西。

Do decorators add significant overhead to a system? I can't find anything to back that up.

推荐答案

使用装饰器增加的开销应该只是一个额外的函数调用

The overhead added by using a decorator should be just one extra function call.

装饰器所做的工作不是开销的一部分,因为您的替代方法是将等效代码添加到装饰的对象中。

The work being done by the decorator isn't part of the overhead as your alternative is to add the equivalent code to the decorated object.

所以装饰功能可能要花两倍的时间才能运行,但这是因为装饰器正在做一些重要的工作,而与未装饰的功能所花费的时间大致相同。

So it's possible that the decorate function takes twice as long to run, but that's because the decorator is doing some important work that takes roughly the same time to fun as the undecorated function.

这篇关于装饰器给Python函数调用增加了多少开销的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆