Facebook reported a sharp rise in second-quarter profit as ad sales surged 47 percent from a year ago.