Let us consider the mass distribution of a collection of particles of masses $m_i$ at coordinate positions $\vec{x}_i$. We neglet nongravitational interaction, which assumes the fluctuations from homogeneity are appreciable only on scales small compared to the Hubble length, and peculiar motion is nonrelativistic. In this limit the Lagrangian for the system is
\[L = \frac{1}{2}\sum\limits_i {{m_i}{a^2}\dot{\vec{x}_i^2} - MV}. \]
The sum is over the kinetic energy of the particles in some large comoving volume. The total mass in this volume is $M=\sum_{i} m_{i}$. The gravitational potential energy per unit mass is
\[V = - \frac{1}{2}\frac{G{a^5}}{M}
\int {{d^3}{x_1}} {d^3}{x_2}\frac{\left[ {\rho \left( {x_1} \right)-{\rho _b}} \right]
\left[ {\rho \left( {x_2} \right) - {\rho _b}} \right]}
{x_{12}}.\]
It is determined by the difference between the local mass density $\rho(\vec{x})$ and its mean value $\rho_b$.
The momentum of the $i$-th particle
\[{\vec p_i} = \frac{\partial L}
{\partial \dot{\vec{x}}_i}
= {m_i}{a^2}{\dot{\vec{x}}_i}\]
and the Hamiltonian is
\[H = \sum\limits_i
{\frac{\vec p_i^2}{2{m_i}{a^2}}} + MV
= M(K + V).\]
We introduce the dimensionless mass autocorrelation function
\[\xi \left( {\left| {{{\vec r}_1} - \vec r} \right|} \right)
= \frac{\left[ {\rho(x_1) - {\rho _b}} \right]
\left[\rho(x_2) -\rho_b\right]}{\rho _b^2}.\]
With the change of variables to $\vec x = {\vec x_1} - {\vec x_2}$ and using $M = {a^3}\int {{d^3}x{\rho _b}}$, for the potential energy we obtain
\begin{align*}
V &= - \frac{1}{2}G{\rho _b}{a^2}
\int {{d^3}x\frac{\xi (x)}{x}}
= - 2\pi G{\rho _b}{J_2},\\
J_2&\equiv \int\limits_0^\infty {\xi (r)dr}
\end{align*}
Then from
\[\frac{dH}{dt} = \frac{\partial H}{\partial t}\]
where the partial derivative is computed at fixed particle coordinates and momenta. At fixed $\vec{x}_i$ and $\vec{p}_i$ we have $K\sim a^{-1}$ and $V \sim {\rho _b}{a^2} \propto {a^{ - 1}}$. So the last equation is reduced to
\[\frac{dE}{dt}= \frac{d}{dt}(K + V) = - \frac{\dot a}{a}(2K + V).\]
This equation is known as the cosmic energy or the Layzer-Irvine equation$^*$.
$^*$It was derived independently in W.~M.~Irvine, Ph.D. thesis, Harvard University, (1961) and D.~Layzer, Astrophys. J. 138, 174 (1963).