An optimal dynamic decoupling of a quantum system coupled to a noisy environment must take into account also the imperfections of the control pulses. We present a formalism which describes, in a closed-form expression, the evolution of the system, including the spectral function of both the environment and control noise. We show that by measuring these spectral functions, our expression can be used to optimize the decoupling pulse sequence. We demonstrate this approach with an ensemble of optically trapped ultracold rubidium atoms, and use quantum process tomography to identify the effect of the environment and control noise. Our approach is applicable and important for any realistic implementation of quantum information processing.