What is the os.times() method in Python?

The os module

The os module in Python provides functions that help in interacting with the underlying operating system.

The times() method

The times() method returns the current global process times. The current global process timings are represented as a tuple-like object with five named properties that are returned by this function. These five attributes are as follows:

  • user: This attribute represents the user time.
  • system: This attribute represents the system time.
  • children_user: This attribute represents the user time of all the child processes.
  • children_system: This attribute represents the system time of all the child processes.
  • elapsed: This attribute represents the elapsed real time since a fixed point in the past.

Syntax

os.times()

Parameters

This method has no parameters.

Code

import os
diff_times = os.times()
print("User time - ", diff_times.user)
print("System time - ", diff_times.system)
print("Children User time - ", diff_times.children_user)
print("Children System time - ", diff_times.children_system)
print("Elapsed time - ", diff_times.elapsed)

Code explanation

  • Line 1: The os module is imported.
  • Line 3: The global times of the current process are obtained using the os.times() method.
  • Line 5: The user time is obtained as a user property of the diff_times object. The user time can also be obtained using diff_times[0].
  • Line 6: The system time is obtained as a system property of the diff_times object. The system time can also be obtained using diff_times[1].
  • Line 7: The children user time is obtained as children_user property of the diff_times object. The children_user time can also be obtained using diff_times[2].
  • Line 8: The children system time is obtained as a children_system property of the diff_times object. The children_system time can also be obtained using diff_times[3].
  • Line 9: The elapsed time is obtained as the elapsed property of the diff_times object. The elapsed time can also be obtained using diff_times[4].