高性能的Python扩展:第一部分

发表于:2014-11-28 10:49

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:J. David Lee    来源:51Testing软件测试网采编

  简介
  通常来说,Python不是一种高性能的语言,在某种意义上,这种说法是真的。但是,随着以Numpy为中心的数学和科学软件包的生态圈的发展,达到合理的性能不会太困难。
  当性能成为问题时,运行时间通常由几个函数决定。用C重写这些函数,通常能极大的提升性能。
  在本系列的第一部分中,我们来看看如何使用NumPy的C API来编写C语言的Python扩展,以改善模型的性能。在以后的文章中,我们将在这里提出我们的解决方案,以进一步提升其性能。
  文件
  这篇文章中所涉及的文件可以在Github上获得。
  模拟
  作为这个练习的起点,我们将在像重力的力的作用下为N体来考虑二维N体的模拟。
  以下是将用于存储我们世界的状态,以及一些临时变量的类。
# lib/sim.py
class World(object):
"""World is a structure that holds the state of N bodies and
additional variables.
threads : (int) The number of threads to use for multithreaded
implementations.
STATE OF THE WORLD:
N : (int) The number of bodies in the simulation.
m : (1D ndarray) The mass of each body.
r : (2D ndarray) The position of each body.
v : (2D ndarray) The velocity of each body.
F : (2D ndarray) The force on each body.
TEMPORARY VARIABLES:
Ft : (3D ndarray) A 2D force array for each thread's local storage.
s  : (2D ndarray) The vectors from one body to all others.
s3 : (1D ndarray) The norm of each s vector.
NOTE: Ft is used by parallel algorithms for thread-local
storage. s and s3 are only used by the Python
implementation.
"""
def __init__(self, N, threads=1,
m_min=1, m_max=30.0, r_max=50.0, v_max=4.0, dt=1e-3):
self.threads = threads
self.N  = N
self.m  = np.random.uniform(m_min, m_max, N)
self.r  = np.random.uniform(-r_max, r_max, (N, 2))
self.v  = np.random.uniform(-v_max, v_max, (N, 2))
self.F  = np.zeros_like(self.r)
self.Ft = np.zeros((threads, N, 2))
self.s  = np.zeros_like(self.r)
self.s3 = np.zeros_like(self.m)
self.dt = dt
31/3123>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号