Counting sheep is a mental exercise used in some Western cultures as a means of putting oneself to sleep.

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 effectiveness of the method may depend upon the mental power required. An experiment conducted by researchers at Oxford University, though not involving livestock as the object of visualization, found that subjects who imagined "a beach or a waterfall" were forced to expend more mental energy, and fell asleep faster, than those asked to "simply distract from thoughts, worries and concerns." Sleep could be achieved by any number of complex activities that expend mental energy.

An early reference to counting sheep can be found in he early twelfth-century Spanish work "Disciplina Clericalis" (collection of fables and tales and is the oldest European book of its kind). "Disciplina Clericalis" draws mainly on literary sources from the Islamic world. Counting sheep was probably a widely recognized practice in the Islamic world before the early twelfth century.

More Info: en.wikipedia.org