I am writing a script to simulate the spins. I have used "For" loop, but the execution takes long time as I have a lot of dataset. Has there any way to make it faster ? Here is the code:
Ix = 1/2 {{0, 1}, {1, 0}}; Iy = 1/2 {{0, -I}, {I, 0}}; Iz = 1/2 {{1, 0}, {0, -1}}; Io = IdentityMatrix[2]; I1z = KroneckerProduct[Iz, Io]; I2z = KroneckerProduct[Io, Iz]; I1x = KroneckerProduct[Ix, Io]; I2x = KroneckerProduct[Io, Ix]; I1y = KroneckerProduct[Iy, Io]; I2y = KroneckerProduct[Io, Iy]; \[Rho]1={{1/2, 0, I/2, 0}, {0, -(1/2), 0, I/2}, {-(I/2), 0, 1/2, 0}, {0, -(I/2), 0, -(1/2)}} \[Omega]D = 2 \[Pi] 20; \[Omega]CS = 2 \[Pi] 5 ; \[Omega]r = 2 \[Pi] 15; \[Gamma] = \[Beta] = \[Pi]/4; aq = 100(*ms*); DwL = 0.002(*Dwell time in ms*); time = Table[i, {i, 0, aq, DwL}]; U0t = ConstantArray[0, {Length@time - 1, 2, 2}]; \[Rho]t = ConstantArray[0, {Length@time, 2, 2}]; Mxt = Myt = ConstantArray[0, Length@time - 1]; H0 = \[Omega]D (\[Sqrt]2 Sin[ 2 \[Beta]] Cos[\[Omega]r t + \[Gamma]] - (Sin[\[Beta]])^2 Cos[ 2 \[Omega]r t + 2 \[Gamma]]) (2 I1z.I2z - I1x.I2x - I1y.I2y) + \[Omega]CS (-\[Sqrt]2 Sin[ 2 \[Beta]] Cos[\[Omega]r t + \[Gamma]] + (Sin[\[Beta]])^2 Cos[ 2 \[Omega]r t + 2 \[Gamma]]) (I1z + I2z); integrals = Table[Integrate[H0, {t, time[[i]], time[[i + 1]]}],{i, 1, Length@time - 1}]; For[i = 1, i < Length@time, i++, dt = time[[i + 1]] - time[[i]]; U0t[[i]] = MatrixExp[-I integrals[[i]]]; \[Rho]t[[i]] = U0t[[i]].\[Rho]1.U0t[[i]]\[ConjugateTranspose]; Mxt[[i]] = Tr[\[Rho]t[[i]].I1x]; Myt[[i]] = Tr[\[Rho]t[[i]].I1y]; ] Any suggestion will be really helpful!

Forloop. Once it's rewritten in more structured form, it'll almost certainly be faster, easier to parallelize, and much easier to see where speed could be improved. $\endgroup$Integrateuses the numeric branch here, because the interval endpoints are machine precision numbers. The problem is just that this are so many integrals. So the key here is actually to do the integral symbolically once. ;) $\endgroup$