在图形上绘制多个图形时避免for循环

时间:2019-08-29 21:45:43

标签: python performance for-loop matplotlib plot

我正在绘制大约10000次迭代的误差函数值,并且绘制它们会花费很多时间。 我想尽可能避免将for-loop绘制在一个图中,但还是要加快速度。

void setup() {
  size(600, 600, OPENGL);
  for (int x = -1; x <= 1; x++) {
    for (int y = -1; y <= 1; y++) {
      for (int z = -1; z <= 1; z++) {
        PMatrix3D matrix = new PMatrix3D();
        matrix.translate(x, y, z);
        cube[index] = new Cubie(matrix, x, y, z);
        index++;
      }
    }
  }
}

void draw() {
  //processing-setup-skit, rör inte hur som helst...
  background(51); 
  rotateX(-0.5);
  rotateY(0.4);
  rotateZ(0.1);
  scale(50);

  for (int i = 0; i < cube.length; i++) {
    push();
    if (abs(cube[i].z) > 0 && cube[i].z == currentMove.z) {
      rotateZ(currentMove.angle);
    } else if (abs(cube[i].x) > 0 && cube[i].x == currentMove.x) {
      rotateX(currentMove.angle);
    } else if (abs(cube[i].y) > 0 && cube[i].y == currentMove.y) {
      rotateY(-currentMove.angle);
    }   
    cube[i].show();
    pop();
  }
}

尝试的时间是:

import time
import matplotlib.pyplot as plt
a = time.time()

for one in range(len(data)):
    plt.plot(data[one],"-o")
plt.show() 

b = time.time()
print(b-a)

但是它没有显示任何情节。因此,我的目标是加快绘制速度,并在出现瓶颈的情况下删除for-loop。

数据是

(plt.plot(data[one],"-o") for one in range(len(data)))
plt.show()

如果有关系,x轴可以视为

data = array([[  0. ,   0. ,   0. ,   0. ,   0. ],
       [-43.4, -18. , -10.5,  -7.4,  -5.7],
       [ 25.7,  18.3,  13.8,  10.7,   8.6],
       [-25. , -10. ,  -5.8,  -4.2,  -3.3],
       [ 16.1,  11.5,   8.6,   6.5,   5.1],
       [-16.2,  -6.4,  -3.8,  -2.9,  -2.4],
       [  9.6,   7.1,   5.2,   3.8,   2.9],
       [ -9.1,  -3.4,  -2. ,  -1.6,  -1.5],
       [  4.7,   3.9,   2.9,   2. ,   1.4],
       [ -4.5,  -1.3,  -0.7,  -0.8,  -0.8]])

1 个答案:

答案 0 :(得分:0)

这有点“作弊”,但是您可以使用并行处理器包装python函数。例如,如果您有8核处理器,则可以使用7核并行运行功能,或者使其速度提高7倍。

import matplotlib.pyplot as plt
from multiprocessing import Pool, cpu_count

def multi_processor(function_name):

    # Use max number of system processors - 1
    pool = Pool(processes=cpu_count()-1)
    pool.daemon = True

    results = {}
    # for every item in your list of items, start a new process
    for one in range(len(data)):
        results[one] = pool.apply_async(your_function, args=(data[one]))

    # Wait for all processes to finish before proceeding
    pool.close()
    pool.join()

    # Results and any errors are returned
    return {your_function: result.get() for your_function, result in results.items()}

def your_function(arg1):
    try:
        return plt.plot(arg1,"-o")
    except Exception as e:
        return str(e)

if __name__ == "__main__":
    multi_processor("your_function")
    plt.show()