dnd 5e – When do I have to declare that I want to twin my spell?

From Metamagic section, Twinned Spell (PHB, p. 102):

When you cast a spell that targets only one creature and doesn’t have a range of self, you can spend a number of sorcery points equal to the spell’s level to target a second creature in range with the same spell (1 sorcery point if the spell is a cantrip).

“When” you cast the spell means that you must declare that you want to use the Twinned Spell Metamagic before the attack roll has been resolved.

This makes sense considering that you are targeting a second creature with the same casting of that spell. If you declared the use of Twinned Spell any later than before the attack roll, then it would be as though you are gaining a second attack, a second casting of the same spell.

Unfortunately, this does mean that, if your attack misses, the sorcery points are wasted.