zoukankan      html  css  js  c++  java
  • numpy 代码优化(一)—— 常见手段

    选择使用 numpy 库的应有之义就在于:应当以矢量化的方式(vectorized operations)来避免迭代操作(iterations),numpy 下的迭代操作执行起来十分耗时。

    import numpy as np
    
    x = np.linspace(0, 8*np.pi, 100)
    y = np.cos(x)
    
    # 一种矢量化的修改方式
    x[y > 0] = 100

    0. Python 中的循环

    Python 是一种比 C/C# 更为动态的语言。Python 中的循环之所以执行较慢的原因在于,每进入一次循环,CPython 解释器都将执行一些额外的且费时的工作, specifically, it is binding the name x with the next object from the iterator, then when it evaluates the assignment it has to look up the name x again.

    1. np.ndarray 为效率而设计的成员函数:

    • np.ndarray.fill()(通过 C 或者 Fortran 实现):执行多维数组初始化的动作,注意 fill() 函数不是 np 下的全局函数,而是 ndarray 的成员函数;

    2. nditer:numpy 下高效的迭代操作

  • 相关阅读:
    GRUB引导——menu.lst的写法
    条形码类型及常见条形码介绍
    Tmux:终端复用器
    find+*的问题
    find命令之exec
    Linux core 文件介绍
    C语言中返回字符串函数的四种实现方法
    C语言中的volatile
    Stars
    Game with Pearls
  • 原文地址:https://www.cnblogs.com/mtcnn/p/9422243.html
Copyright © 2011-2022 走看看