2.Jupyter Notebook 高级命令

%run 命令

%run myscripts/printhello.py

MachineLearning

同时也把printhello这个函数也加载了进来

printhello('MachineLearning')

Hello MachineLearning !

import mymodule.firstml

导入模块

在文件夹中新建名为 init.py 的脚本文件即可使文件夹变为模块

mymodule.firstml.predict(2)

?

from mymodule import firstml
#另一种导入方法
firstml.predict(9)

?

%timeit 命令

测试代码运行时间

后面只能跟一句代码

%timeit L = [i ** 2 for i in range(1000)]

409 µs ± 7.06 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit L = [i ** 2 for i in range(1000000)]

460 ms ± 29.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

可以看出,运算时间基本成线性关系,数据扩大十倍,运算时间也变为10倍

%%timeit 命令

测试代码运行时间

后面跟一段代码

%%timeit 
L = []
for i in range(1000):
    L.append(i ** 2)

461 µs ± 10.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

在python中的for循环速度要慢一些

但是上述命令会让代码运行多次,我们只希望运行一次则需要用到下述命令

%time

后面只能跟一句代码

%time L = [a ** 2 for a in range(10000)]

Wall time: 0 ns

%%time

后面跟一段代码

%%time
L = []
for i in range(10000):
    L.append(i ** 2)

Wall time: 10 ms

import random
L =  [random.random() for i in range(100000)]
%time L.sort()

Wall time: 20.1 ms

L =  [random.random() for i in range(100000)]
%timeit L.sort()

1.7 ms ± 129 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

其他魔法命令

查看某一命令的文档,输入格式:命令?

%lsmagic

Available line magics:
%alias %alias_magic %autoawait %autocall %automagic %autosave %bookmark %cd %clear %cls %colors %conda %config %connect_info %copy %ddir %debug %dhist %dirs %doctest_mode %echo %ed %edit %env %gui %hist %history %killbgscripts %ldir %less %load %load_ext %loadpy %logoff %logon %logstart %logstate %logstop %ls %lsmagic %macro %magic %matplotlib %mkdir %more %notebook %page %pastebin %pdb %pdef %pdoc %pfile %pinfo %pinfo2 %pip %popd %pprint %precision %prun %psearch %psource %pushd %pwd %pycat %pylab %qtconsole %quickref %recall %rehashx %reload_ext %ren %rep %rerun %reset %reset_selective %rmdir %run %save %sc %set_env %store %sx %system %tb %time %timeit %unalias %unload_ext %who %who_ls %whos %xdel %xmode

Available cell magics:
%%! %%HTML %%SVG %%bash %%capture %%cmd %%debug %%file %%html %%javascript %%js %%latex %%markdown %%perl %%prun %%pypy %%python %%python2 %%python3 %%ruby %%script %%sh %%svg %%sx %%system %%time %%timeit %%writefile

Automagic is ON, % prefix IS NOT needed for line magics.

posted on 2022-03-31 21:11  饮冰未  阅读(121)  评论(0编辑  收藏  举报