如何衡量Python中的关系比较效率?(How to measure relational comparison efficiency in Python? [closed])

编程入门 行业动态 更新时间:2024-10-28 16:17:27
如何衡量Python中的关系比较效率?(How to measure relational comparison efficiency in Python? [closed])

我正在研究CodeFights上的一些计算机科学问题然后我发现了这个问题,起初我无法理解为什么第一种方法被认为是这种情境的最佳实现。

有人可以给我指导如何衡量Python中的关系比较编码效率吗?

你想编写一个函数,它将整数x,y,L和R作为参数,如果xy位于区间(L,R)则返回True,否则返回False。你正在考虑几种方法在里面写一个条件语句这个功能:

if L < x ** y <= R: if x ** y > L and x ** y <= R: if x ** y in range(L + 1, R + 1):

I'm working on some Computer Science problems on CodeFights and then I found this problem, At first I couldn't understand why the first approach is considered as the best implementation for this context.

Can someone give me guidance on how to measure the relational comparison coding efficiency in Python?

You would like to write a function that takes integer numbers x, y, L and R as parameters and returns True if xy lies in the interval (L, R] and False otherwise. You're considering several ways to write a conditional statement inside this function:

if L < x ** y <= R: if x ** y > L and x ** y <= R: if x ** y in range(L + 1, R + 1):

最满意答案

对于微型标记小片段,请查看timeit模块 。

为了记录,我强烈怀疑return L < x ** y <= R将是最有效的解决方案; 它只计算x ** y一次,短路,并且不构造其他对象。 它还直接使用测试结果,而不是使用if控制显式return True或return False 。 如果你必须选择,等同的检查将是最快的; range测试在理论上同样快,但构建range对象,即使在Py 3中,也会有很高的固定成本,而且包容测试不会弥补。

For microbenchmarking small snippets, take a look at the timeit module.

For the record, I strongly suspect return L < x ** y <= R will be the most efficient solution; it computes x ** y only once, short-circuits, and constructs no additional objects. It also uses the result of the test directly, rather than using if checks controlling explicit return True or return False. The equivalent if check would be the fastest if you have to choose; range tests are equally fast in theory, but constructing the range object, even in Py 3, would have a high fixed cost that the containment test wouldn't make up.

更多推荐

本文发布于:2023-08-05 08:14:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1428749.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:效率   关系   measure   Python   efficiency

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!