<jupyter_start><jupyter_text>1. % magic 指令   1.1 测试代码运行时间 time% 开头为行命令, %% 开头为 cell 命令.%timeit 用于测试单行语句的执行时间,会重复计算多次.%%timeit 用于测试整个单元中代码的执行时间.  %time 则只输出本次执行消耗的时间.<jupyter_code>%%time
a = []
for i in range(10):
    a.append(i)<jupyter_output>CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 30 µs<jupyter_text>1.2 捕获程序输出信息   %%capture将单元格的输出保存为一个对象.<jupyter_code>%%capture time_results
import random
for n in [1000, 5000, 10000, 50000, 100000,500000]:
    print "n = {0}".format(n)
    alist = range(n)
    %time random.shuffle(alist)
print time_results.stdout<jupyter_output>n = 1000
CPU times: user 4 ms, sys: 0 ns, total: 4 ms
Wall time: 1.48 ms
n = 5000
CPU times: user 12 ms, sys: 0 ns, total: 12 ms
Wall time: 7.02 ms
n = 10000
CPU times: user 16 ms, sys: 0 ns, total: 16 ms
Wall time: 13 ms
n = 50000
CPU times: user 52 ms, sys: 4 ms, total: 56 ms
Wall time: 51.1 ms
n = 100000
CPU times: user 44 ms, sys: 0 ns, total: 44 ms
Wall time: 46.2 ms
n = 500000
CPU times: user 216 ms, sys: 0 ns, total: 216 ms
Wall time: 217 ms<jupyter_text>1.3 性能分析%%prun 命令调用 profile 模块对单元中的代码进行性能分析.1.4 代码调试%debug命令用于调试代码.一种是在执行代码之前设置断点进行调试;另一种是在代码抛出异常之后,执行%debug命令查看调用堆栈.<jupyter_code>import os
ipython = get_ipython()
print ipython.ipython_dir
print ipython.config.ProfileDir.location<jupyter_output>/home/klm/.ipython
<traitlets.config.loader.LazyConfigValue object at 0x7f14080bacd0>
{'fraction_non_alphanumeric': 0.11279826464208242, 'fraction_numerical': 0.09544468546637744, 'mean_word_length': 4.7907949790794975, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '418680', 'license': 'MIT', 'n_tokens_mistral': 777, 'n_tokens_neox': 718, 'n_words': 173, 'path': 'develop_language/python/doc/science_compute/ipynb_files/chapter1.ipynb', 'repo_name': 'magic428/subjects_notes', 'size': '1383'}