Surely the answer as to why it evolved is obvious - it takes more energy during development (and a lot of selective pressure during evolution) to make a reproductive system that produces pleasure
only during reproductive sex acts than one that can produce pleasure in non-reproductive situations. Hence, masturbation exists.
I love the statistic that male Macaques spend 1-6% of their metabolism on production of ejaculate though.