In Valve games you are able to record demos that capture every tick of information, so players will record a full set of demos then put them into a program that counts the number of ticks. In Portal 2 (dunno about Portal) the tick rate is 60 Hz, so the time is ticks/60 (which is why any times you see down to the millisecond will be multiples of 1/60).
Exceptions are made at the start and end of a run for when the player actually gets control, usually deemed to be when the crosshair appears/disappears. Runners will open up the demos, step through them frame-by-frame watching the crosshair, then subtract that many ticks.
More generally as to how speed runs are "officially" timed, the most "official" (notice the quotes) body I know for speed-runs would be the Speed Demos Archive, who maintain a decent amount of runs across various platforms. They have an FAQ about how to time runs, but some communities can be strong enough to add game- or engine-specific exceptions to their general guidelines.
If a game displays a time upon completion, and this time is tested to be accurate, then the timer will be used. An example of an inaccurate game timer is one that doesn't display the exact time when a player saves, such as Star Ocean 2's timer, which drops seconds when saving. Some game timers don't count time at pause/inventory screens, dialogs, cutscenes, etc., so the time can be significantly less than the video length. Some games have a timer but it can't be seen at the end of the game. In most of those cases the timer will be ignored. For some games like RPGs, however, such timers are displayed in a menu screen that you would be looking at before the final battle; that time will be noted and real time from that point added on.
For games without timers, a simple real-time measure is used. When the player first gains control of the game's character, timing begins. At the end when control is lost, even if that's long after the final battle, the timing stops. Possible movement that can occur during or after the ending credits does not count. For segmented runs, timing for a segment stops at the first system-dependent activity, usually the actual saving. When loading, the timing resumes at the point when the game was saving or displaying the password. For runs over three hours, the seconds are dropped because slight variations in recording speed can become significant.