Python Forum
Help to reduce time to execute the code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help to reduce time to execute the code
#1
Dear Sir,
I have written a code to calculate the magnetic field due to a current loop located in XY-plane. But the code takes 60 minutes to execute. Please help me to reduce it.

import numpy as np
from scipy.spatial import distance_matrix
 
import time
 
t1=time.time()
n=20
# -------------- Poisition point of grid------------
x = np.array(np.linspace(-1,1,n))
y = np.array(np.linspace(-1,1,n))
z = np.array(np.linspace(-1,1,n))
 
X,Y,Z=np.meshgrid(x,y,z)
#----Making array of position vector in calculation grid space-----------
pos_vec=np.transpose([np.repeat(x,len(z)*len(y)),np.tile(np.repeat(y,len(z)),len(x)),np.tile(z,len(x)*len(y))])
#   -------- Position Points of Loop------------
t=np.linspace(0,1,n) # n-points of wire loop in XY plane 
x_loop=np.sin(2*np.pi*t)
y_loop=np.cos(2*np.pi*t)
z_loop=np.zeros(n)
loop_vec=np.transpose([x_loop,y_loop,z_loop])
# ----------- length of dl and mid point of dl-----------
p_source=np.empty((n,3),float)
dl=np.empty((n,3),float)
for i in range(0,n-1):
    p_source[i]=((loop_vec[i+1,:]+loop_vec[i,:])/2) # position of Delta-1 (mid-point)
    dl[i]=(loop_vec[i+1,:]-loop_vec[i,:])          # Delta-1 vector
R_vec=(distance_matrix(loop_vec,pos_vec)) # data set having four array, each is distance (r) from each dl point to all other points in space grid
R_4point_loop=np.transpose(R_vec) # Set of four r's from four dl point to a single calculation point 
#################Functions ############################
###### Normalized Vector (Unit Vector function)########
def normalize(v):
    norm=np.linalg.norm(v, ord=1)
    if norm==0:
        norm=np.finfo(v.dtype).eps
    return v/norm
###### Calculating B-field ############################
def B(dl,r_pos,r):
    i = 1                                          #Amps in the wire
    mu = 1.26 * 10**(-6)                            #Magnetic constant
    return ((mu/(2*np.pi))*(i/r**3))*np.cross(normalize(dl),normalize(r_pos)) #Magnitude of the vector B
 
# -------- Making empty vectors---------
B_total=np.empty((len(x)*len(y)*len(z),3),dtype=float)
B_dl=np.empty((n,3),float)
B_point=np.empty((1,3),float)
for r_end in pos_vec:
    B_dl*=0.0
    B_point*=0.0
    s=0
    for i in range(n):
        B_dl[i]=np.array(B(dl[i],r_end,R_4point_loop[i][s]))
        s+=1
        B_point+=B_dl[i]
    B_total[s]=B_point
            
# Three components of data
x_bfield=B_total[:,0].reshape(X.shape)
y_bfield=B_total[:,1].reshape(X.shape)
z_bfield=B_total[:,2].reshape(X.shape)
t2=time.time()
Elapsed=float(str(t2-t1))
print("Time of excecution (s):%.4f"%Elapsed)
Reply
#2
Main issue here is two nested loops (lines 47, 51). To improve performance without changing the code you can try to use
numba jit compiler. However, I think it is possible totally vectorize your calculations and avoid loops at all. At least, lines 25-27 could be reduced as follows:

p_source = (loop_vec[1:, :] + loop_vec[:-1, :]) / 2 # note you initialize p_source with shape 20, 3
dl = (loop_vec[1:, :] - loop_vec[:-1, :])
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  reduce nested for-loops Phaze90 11 1,760 Mar-16-2023, 06:28 PM
Last Post: ndc85430
  Adding values with reduce() function from the list of tuples kinimod 10 2,515 Jan-24-2023, 08:22 AM
Last Post: perfringo
  How can histogram bins be separated and reduce number of labels printed on x-axis? cadena 1 852 Sep-07-2022, 09:47 AM
Last Post: Larz60+
  Can a program execute code in iPython shell and get result? deanhystad 3 1,664 Jun-17-2022, 03:45 AM
Last Post: Larz60+
  Assistance with running a few lines of code at an EXACT time nethatar 5 3,166 Feb-24-2021, 10:43 PM
Last Post: nilamo
  Stumped by my own code (ratio & epoch-time calculation). MvGulik 2 2,090 Dec-30-2020, 12:04 AM
Last Post: MvGulik
  How do I reduce the time to Invoke Macro via Python? JaneTan 1 2,076 Dec-28-2020, 06:46 AM
Last Post: buran
  Code taking too much time to process ErPipex 11 4,820 Nov-16-2020, 09:42 AM
Last Post: DeaD_EyE
  What is the run time complexity of this code and please explain? samlee916 2 2,258 Nov-06-2020, 02:37 PM
Last Post: deanhystad
  The count variable is giving me a hard time in this code D4isyy 2 1,929 Aug-09-2020, 10:32 PM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020