The Movistar rider, fourth overall last year, crossed the line in 5:58:17 with Ewan (Lotto-Soudal) and Diego Ulissi (UAE Team Emirates) completing the podium in the same time.
They were part of a group of seven riders, including Valerio Conti (UAE Team Emirates), who went clear after dodging a fall about 6km from the end.
Tom Dumoulin (Sunweb), a victim of the crash, was the biggest loser among the GC contenders.
“Yes, it was the perfect attack,” Carapaz told reporters afterwards. “I knew it would be hard to beat the sprinters, so I had to anticipate the action and I did it at the right moment.”
Earlier, Marco Frapporti (Androni-Sidermec), Mirco Maestri (Bardiani-CSF) and Damiano Cima (Nippo-Fantini-Faizanè) were in a stage-long breakaway, building a lead of 12:35.
With 20km to go and with their advantage quickly being whittled down, Frapporti attacked and dragged Maestri with him. However, the chase of the peloton was relentless and the duo shook hands when they conceded defeat with 10km to go.
“In a Grand Tour it is important to avoid the bad things that can happen,” Roglic said afterwards. “In time-trials and on mountains you know what will happen and it is quite easy to control.
“Stages like these I think are just super nervous and in the end we just want to come safe to the finish.”
Giulio Ciccone (Trek-Segafredo) leads the king of the mountains competition and Miguel Angel Lopez (Astana) the young rider classification.
The fifth stage of the Giro d’Italia will be contested over 140km from Frascati to Terracina.