This is done by the kernel scheduler, when a process is scheduled to run, the time it is running is added to the total for that process. The scheduler chooses a process to run 100 to 1000 times per second, depending on the OS and the configuration. (This amount of time is the time slice.)
A sleep(10)
will use less than a microsecond of CPU time because it causes the process to stop running. The scheduler will then choose another process to begin running (or if there are none that are ready to run, the CPU can go idle). A timer will then be created for the process that expires in 10
seconds. At that time, the scheduler will then choose the process to run on the CPU at the next available time slice.
Operations involving file I/O will also cause the process to stop running while the CPU waits for the disk or network to be ready, so they will not use much CPU time either.
Operations that do take CPU time would be those that read/write variables, do numeric math operations, build and scan string variables, loops and if statements.
There is no simple formula to tell how much CPU time will be used by a given program. It depends on what exactly the program does. The typical web page that is just reading/writing a database will not use very much CPU time.