jupyter notebook中的魔法命令%run和%timeit

时间:2022-07-23
本文章向大家介绍jupyter notebook中的魔法命令%run和%timeit,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

jupyter notebook作为一个强大的python IDE,有一些自带的魔法命令(Magic Command),可以帮我我们高效的运行程序 。

1. %run

%run后面写python脚本的路径,可以直接执行该py文件并且加载到jupyter中。 有如下的python文件greet.py:

def greet(name):
    print("Hello, {}!".format(name))

greet('Daming')

在jupyter中导入:

%run ~/Documents/writethings/20200818/greet.py
greet('Wang')

可以看到已经成功运行并且加载进来了。

2. %timeit

jupyter测试了1000个loop,然后得出了mean+-sd的时间。

但是当我们的程序要运行很长时间时:

jupyter会根据程序的时长来判断loop的次数。

注意%timeit后边只能接一句程序。

如果我们需要测试一段代码的时间,则可以用%%timeit:

如果想知道说明的话,可以输入%run?来查询: