蟒蛇 |效率和性能
假设我要通过运行单个脚本在列表中保存 100 个浮点数,很可能需要一些内存来处理。因此,如果此代码每次作为应用程序的要求执行,则会影响性能,所以我的问题是如何保持效率以获得绩效。
模拟代码:
def generate_lglt():
float1, float2 = 27.2423423, 12.2323245
lonlats = []
for val in range(100, 0, -1):
lonlats.append(random.uniform(float1, float2))
lonlats.append(random.uniform(float1, float2))
lonlats.append(random.uniform(float1, float2))
lonlats.append(random.uniform(float1, float2))
lonlats.append(random.uniform(float1, float2))
print lonlats
谢谢。
Lets say I'm going to save 100 floating point numbers in a list by running a single script, most probably it will take some memory to process.So if this code executes every time as a requirement of an application there will be performance hits, so my question is how to maintain efficiency in order to gain performance.
Mock-up code:
def generate_lglt():
float1, float2 = 27.2423423, 12.2323245
lonlats = []
for val in range(100, 0, -1):
lonlats.append(random.uniform(float1, float2))
lonlats.append(random.uniform(float1, float2))
lonlats.append(random.uniform(float1, float2))
lonlats.append(random.uniform(float1, float2))
lonlats.append(random.uniform(float1, float2))
print lonlats
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
瓶颈出现在意想不到的地方,因此永远不要仅仅因为您认为代码可能是需要改进的正确代码而对其进行优化。你需要做的就是
cProfile
模块在实际性能测试中分析代码。Bottlenecks occur at unexpected places, so never optimize code just because you think it might be the right code to try to improve. What you need to do is
cProfile
module.如果要多次调用generate_lglt(),您可能希望避免在每次调用代码时重新生成相同的范围(100,0,-1)。您可能希望将生成的范围缓存在某处并一遍又一遍地使用它。
另外,如果要退出 for 循环而不完成每次迭代,请使用 xrange 而不是 range。
If generate_lglt() is going to be called a lot of different times, you may want to keep from regenerating the same range(100,0,-1) with every call of the code. You may want to cache that generated range somewhere and use it over and over again.
Also, if you are going to be exiting a for loop without completing each iteration, use xrange instead of range.