2

我正在创建一个“实时”过程,该过程从由 SierraChart 更新的专有格式 OHLCVTBA 文件中获取数据。读取数据并使用生成器创建数据帧的代码发布在 pastebin 上。[删除死链接]。

我意识到我的结构(新数据驱动)是错误的,我即将对其进行重组。 PhE 的问题和 Wes 的回答使我朝着填充一个运行良好的预填充数据框的方向前进。我的问题是:

将我的数据框和指针作为全局变量保存或将它们传递给使用它们的各种函数是否更快?此外,是否还有其他考虑因素可以推动这种选择?

谢谢。

4

2 回答 2

5

在 python 中,局部变量的访问速度比全局变量快

在 pandas 的上下文中,这意味着您应该将变量传递给有意义的函数(这意味着可以在函数中更快地找到它们)。相反,python 中的函数调用很昂贵(如果你大量调用它们),这就是为什么 numpy/pandas 尽可能使用向量化函数的原因。显然,如果您在函数内执行操作,则必须小心确保所有计算都在原地完成。

在担心速度之前,我通常会先以“pythonic”/“pandastic”的方式让事情发生。然后使用%timeit并查看它是否已经足够快(通常是这样)。添加一个单元测试。调整速度、、%timeit%prun%timeit等等。如果是大项目vbench

于 2013-06-05T09:48:58.890 回答
2

You will need to profile it, but my guess is that if there is any significant difference at all, it is in favor of globals. The reference is still in memory, and no reference counting happens.

(EDIT: anyway, see @Andy Hayden's link about their relative access time, and the link here, which says that local variables are much faster).

The main consideration is that of "software engineering" - using global data is a bad idea, since it's hard to follow when and where it is being changed. Of course, if you can't fulfill the requirements (runtime) otherwise, then it has to be done; but in order to know it - measure first.

Anyway, I would recommend a different solution - keep this data inside a class. It will cost one more dictionary lookup (the first lookup is the variable name, and it happens anyway; the second is the lookup in the class dict), but it may be more efficient than passing around many objects, and will help the organization of your program.

于 2013-06-04T23:32:34.313 回答