Regularity of the Hamiltonian along optimal trajectories