You apply effects when the effect tells you to. You decide to apply the effect prior to the attack roll.
The most obvious generic example of an effect being applied when you attack is your proficiency bonus. The section on proficiency bonus and attacking reads (emphasis mine):
You add your proficiency bonus to your attack roll when you attack using a weapon with which you have proficiency...
Now let's ask two questions:
When is this effect applied?
The effect is applied after you have selected a target to attack and after you have rolled, but before you have determined if your attack roll hit. We can tell this because the wording add ... to your attack roll requires that there is already an attack roll to which we then apply the proficiency bonus.
When do you decide to apply the effect?
This is really the core of your question. Looking at the proficiency bonus, you decide to apply the bonus when you select to attack using a weapon with which you are proficient. Since target viability is determined in part by weapon range, weapon selection is done prior to target selection. The timing of picking a weapon and a target is largely academic and can just be bundled into the targeting part of making an attack.
We can also consider when you attack in context with other abilities.
When you attack vs. When you hit
Paladin's Divine Smite reads:
...when you hit a creature with a melee weapon Attack...
Since it does not say when you attack and then apply the effect on hit, we can deduce that there is an intended mechanical difference between when you attack and when you hit. Because hitting is not guaranteed on an attack, but is guaranteed on a hit, this means that effects that say when you attack have some uncertainty on whether they will take effect. This uncertainty is provided by the attack roll. The attack roll is the break point between the certainty of a when you hit and the uncertainty of when you attack. You decide to use the when you hit after the result of the attack roll has been determined and is a hit. Since when you attack must be on the other side of the break point, it must be decided before the attack roll is made.
FenrirG has pointed out that there is a period between the attack roll and determining if it is a hit. I don't think this changes my argument. Unless another feat is applied during that time (a la Lucky), nothing changes in the game state, other than player knowledge. Since player knowledge does not affect the outcome, my previous point stands.