Counting sheep is a mental exercise used in some cultures as a means of putting oneself to sleep. An early reference can be found in ‘Don Quixote’ by Miguel de Cervantes, from 1605.
Cervantes adapted the story of counting goats from a story of counting sheep in the early twelfth-century Spanish work Disciplina Clericalis, based on literary sources from the Islamic World.
The section The King and his Story-teller (section 12) uses the idea of counting sheep humorously. Counting sheep was probably a widely recognized practice in the Islamic World before the early twelfth century.
In most depictions of the activity, the practitioner envisions an endless series of identical white sheep jumping over a fence, while counting them as they do so.
The idea, presumably, is to induce boredom while occupying the mind with something simple, repetitive, and rhythmic, all of which are known to help Humans sleep.
The reason people count sheep, as opposed to bluebirds or sailboats, is uncertain.
The effectiveness of the method may depend upon the mental power required.