Canonical and microcanonical Monte Carlo simulations are carried out to study the electrocaloric effect (ECE) in ferroelectrics and relaxor ferroelectrics (RFEs) by direct computation of field-induced temperature variations at the ferroelectric-to-paraelectric phase transition and the nonergodic-to-ergodic state transformation. A lattice-based Hamiltonian is introduced, which includes a thermal energy, a Landau-type term, a dipole-dipole interaction energy, a gradient term representing the domain-wall energy, and an electrostatic energy contribution describing the coupling to external and random fields. The model is first parametrized and studied for the case of BaTiO 3 . Then, the ECE in RFEs is investigated, with particular focus on the influence of random fields and domain-wall energies. If the strength or the density of the random fields increases, the ECE peak shifts to a lower temperature but the temperature variation is reduced. On the contrary, if the domain-wall energy increases, the peak shifts to a higher temperature and the ECE becomes stronger. In RFEs, the ECE is maximum at the freezing temperature where the nonergodic-to-ergodic transition takes place. Our results imply that the presence of random fields reduces the entropy variation in an ECE cycle by pinning local polarization.