怎么运行ipython,如何从脚本运行IPython魔术(或定时Python脚本)

本文讨论了如何在Python脚本中模拟IPython的%timeit魔法命令来测量代码运行时间。作者指出timeit模块存在一些缺点,如无法自适应选择运行次数。通过引入IPython的%timeit命令,可以更方便地自动化这个过程。文章建议参考MATLAB的类似代码,并询问如何在Python脚本中调用%timeit。解决方案提供了在不同IPython版本下调用该命令的方法。
摘要由CSDN通过智能技术生成

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()

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).

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

解决方案

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

from IPython import get_ipython

ipython = get_ipython()

If you have an older version:

import IPython.core.ipapi

ipython = IPython.core.ipapi.get()

or

import IPython.ipapi

ipython = IPython.ipapi.get()

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

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

Note that the script must be run via ipython.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值