Simply, a company called Nielsen in the US gives special boxes to random samplings of people. The box monitors what is displayed on the TV, and reports back to the company. Alternatively, people write in "TV Diaries" documenting what they've watched.
http://en.wikipedia.org/wiki/Nielsen_Ratings
http://entertainment.howstuffworks.com/question433.htm