Windows系统Jupyter Notebook中%%time无法返回CPU时间,如何获取?
在Windows 10的Jupyter Notebook中获取CPU时间的解决方案
当然可以在Windows系统中获取CPU时间!问题出在Jupyter内置的%%time魔法命令在不同操作系统上的实现差异——它在Linux/Unix系统会自动捕获并显示用户态、内核态的CPU时间,但在旧版本的Jupyter(搭配Python3.6 Anaconda)的Windows环境中,默认只展示墙钟(Wall time)时间。
下面给你几个实用的解决方法,按易用性和详细程度排序:
方法一:手动用标准库time模块统计CPU时间
Python标准库的time.process_time()专门用于统计当前进程的CPU时间(用户态+内核态总和,不包含进程睡眠等待的时间),完全跨平台。直接在代码块中加入统计逻辑即可:
import time # 记录CPU时间起始点 start_cpu = time.process_time() # ---------------------- # 这里放你要测试的代码 for i in range(10**6): pass # ---------------------- # 计算并打印CPU时间 end_cpu = time.process_time() print(f"CPU Time: {end_cpu - start_cpu:.4f} seconds")
方法二:自定义专属的CPU时间魔法命令
如果想像%%time一样方便地用一行命令统计,可以在Notebook中自定义一个魔法命令,之后就能重复使用:
from IPython.core.magic import register_cell_magic import time @register_cell_magic def cputime(line, cell): # 记录CPU起始时间 start = time.process_time() # 执行代码块内容 exec(cell, globals()) # 计算并输出CPU时间 end = time.process_time() print(f"CPU Time: {end - start:.4f} seconds")
定义完成后,直接在代码块开头加上%%cputime就能自动统计CPU时间了:
%%cputime # 你的测试代码 for i in range(10**6): pass
方法三:用psutil获取更详细的CPU时间拆分
如果需要像Ubuntu的%%time那样分开查看用户态、系统态甚至子进程的CPU时间,可以用psutil库(跨平台进程监控工具):
- 先在Anaconda环境中安装psutil:
conda install psutil
- 然后用以下代码统计:
import psutil import time # 获取当前进程对象 process = psutil.Process() # 记录起始CPU时间拆分 start_times = process.cpu_times() # ---------------------- # 你的测试代码 for i in range(10**6): pass # ---------------------- # 记录结束CPU时间拆分 end_times = process.cpu_times() # 计算各部分时间差 user_time = end_times.user - start_times.user system_time = end_times.system - start_times.system print(f"User CPU Time: {user_time:.4f} seconds") print(f"System CPU Time: {system_time:.4f} seconds") print(f"Total CPU Time: {user_time + system_time:.4f} seconds")
额外提示
如果不想自己写代码,也可以尝试升级你的Jupyter版本——较新的Jupyter已经修复了Windows下%%time不显示CPU时间的问题。不过考虑到你用的是Python3.6(比较老的版本),升级可能会有依赖冲突,上面的手动方法会更稳妥。
内容的提问来源于stack exchange,提问作者Eran
相关产品推荐
相关产品推荐

