Relative motions cause rocks to strain out of shape, generating elastic stress. When the stress exceeds the strength of the fault zone, the accumulated strain will suddenly release in an earthquake. The sudden release of stored elastic potential energy during an earthquake releases both heat energy and seismic waves. The total energy is called the moment M0. By essentially taking the logarithm of the moment, we can create a magnitude rating.
Every earthquake has a unique total energy, and therefore a unique magnitude.
The part of the elastic energy radiated from an earthquake as seismic waves takes two forms, compressional and shear. Sensitive seismographs record the passing ground motions of the seismic waves with respect to time, noting the motions of an inertial mass against the moving ground. Given the fairly constant relation between and distance, you can use the above empirical equation with a calibrated seismograph to estimate an earthquake's magnitude. Of course the distance we get from the S-P time is the distance along the travel path of the seismic waves, so we have to adjust for the earth's spherical shape. Given the S-P times and distances of an earthquake from three stations, we can triangulate to find its location.