in reply to how can I speed this up?

TheoPetersen seems to be on the right path. One thing he showed, but didn't mention was that in your code you tend to build your loops with foreach $it (1..$nt) and then subtract one each time you use $it. A lot of calculations can be saved just by foreach $it <0..$nt-1) That will save some time, but getting away from nested loops will save you more.