如何从脚本运行IPython魔术(或定时Python脚本) [英] How to run an IPython magic from a script (or timing a Python script)

查看:111
本文介绍了如何从脚本运行IPython魔术(或定时Python脚本)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

IPython%timeit magic命令可以很好地测量运行某些Python代码所需的时间。现在,我想在Python脚本中使用类似的东西。我知道timeit模块,但它有几个缺点,例如,如何自适应地选择运行次数?即,默认代码

The IPython %timeit magic command does its job well for measuring time required to run some Python code. Now, I want to use something analogous in the Python script. I know about the timeit module, however, it has several disadvantages, for example, how to select the number of runs adaptively? i.e., the default code

import timeit
t=timeit.Timer("code(f)", "from __main__ import code,f")
t.timeit() 

运行代码数百万次。 %timeit IPyhton magic命令会自动执行此操作。我建议我可以使用类似MATLAB代码的东西
http://www.mathworks.com/matlabcentral/fileexchange / 18798

runs the code million times. The %timeit IPyhton magic command does it automatically. I suggest that I could use something like the MATLAB code http://www.mathworks.com/matlabcentral/fileexchange/18798

自动完成所有工作(并且还会告诉函数的开销是否很大)。

that does all the job automatically (and also tells if the overhead of the function is large).

如何从Python脚本调用%timeit magic(或者可能有更好的时序解决方案)?

How can I call %timeit magic from a Python script (or maybe there is a better timing solution) ?

推荐答案

这取决于你拥有哪个版本的IPython。如果您有1.x:

It depends a bit on which version of IPython you have. If you have 1.x:

from IPython import get_ipython
ipython = get_ipython()

如果你有旧版本:

import IPython.core.ipapi  
ipython = IPython.core.ipapi.get()

import IPython.ipapi  
ipython = IPython.ipapi.get()

完成后,运行如下魔术命令:

Once that's done, run a magic command like this:

ipython.magic("timeit abs(-42)")

请注意,脚本必须通过 ipython 运行。

Note that the script must be run via ipython.

这篇关于如何从脚本运行IPython魔术(或定时Python脚本)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆