IPython%timeit magic命令可以很好地测量运行某些Python代码所需的时间.现在,我想在Python脚本中使用类似的东西.我知道timeit模块,但它有几个缺点,例如,如何自适应地选择运行次数?即默认代码
import timeit
t=timeit.Timer("code(f)", "from __main__ import code,f")
t.timeit()
Run Code Online (Sandbox Code Playgroud)
运行代码数百万次.%timeit IPyhton magic命令会自动执行此操作.我建议我可以使用MATLAB代码 http://www.mathworks.com/matlabcentral/fileexchange/18798
自动完成所有工作(并且还告诉函数的开销是否很大).
如何从Python脚本中调用%timeit magic(或者可能有更好的时序解决方案)?
我正在使用Ubuntu 14.04 LTSAnaconda python安装:
Python 3.5.1 :: Anaconda 2.4.1(64位)
我正在尝试使用此配方在我的ipython笔记本中启用C++交互式编译:
import IPython.core.magic as ipym
@ipym.magics_class
class CppMagics(ipym.Magics):
@ipym.cell_magic
def cpp(self, line, cell=None):
"""Compile, execute C++ code, and return the standard output."""
# Define the source and executable filenames.
source_filename = 'temp.cpp'
program_filename = 'temp.exe'
# Write the code contained in the cell to the C++ file.
with open(source_filename, 'w') as f:
f.write(cell)
# Compile the C++ code into an executable.
compile = self.shell.getoutput("g++ {0:s} -o {1:s}".format( …Run Code Online (Sandbox Code Playgroud) python ipython ipython-notebook ipython-magic jupyter-notebook