From #1 it is evident that parts of the code are slowing down the entire computation. Optimize and speed up the slow parts