You should be able to run this in parallel, see for instance
or
http://jsdokken.com/FEniCS-workshop/src/applications/optimal_control.html#the-gradient-of-the-functional