如何测试 Python 函数完成所需的时间是否少于特定时间
我正在使用Python的单元测试。
我想编写一个测试来确保特定方法在特定时间之前完成。我可以通过通常计算时间戳之后和时间戳之前之间的差异来做到这一点,但我开始想知道
- 这是否通常在TDD,如果方法/函数效率不高,则编写失败的测试,然后重构以使其更高效?
- Python 的单元测试有一个巧妙的方法来做到这一点吗?
I'm using Python's unittest.
I'd like to write a test that ensures a certain method completes before a certain time. I can do this by the usual calculation of the difference between timestamp after and timestamp before, but I started wondering if
- is this commonly done in TDD, write tests that fail if a method / function is not efficient and then refactor to make it more efficient?
- does Python's unittest have a slick way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以用鼻子 @timed 装饰器来完成。我用它来测试计时功能。例子:
You can do it with nose @timed decorator. I use it for testing functions with timing. Example:
一些公司对代码速度进行了测试,类似于回归测试,这些测试试图捕获会减慢系统速度的新代码,如果他们发现问题,您首先尝试修复新代码,使其仍然表现良好,如果您如果无法做到这一点,那么您(产品所有者)可以决定新功能是否值得。
关于 TDD:你不知道运行时间,所以不,你不能通过猜测编写测试,然后重构代码,这样它就会通过..除非你从事非常具体的事情并且有非功能性需求,就像嵌入式系统必须在 50ms 内响应......
Some companies have tests for the speed of code, sort of a regression test, these try to catch new code that slows down the system and if they catch a problem, you first try to fix the new code so it still performs well and if you are not able to do that then you (the product owner) can decide whether the new feature is worth it.
Regarding TDD: You don't know the running time, so no, you can't write a test with a guess and later refactor the code so it will pass.. unless you work on something very specific and have a non-functional requirement, like an embedded system that has to respond within 50ms...