Python's time.clock() vs. time.time() accuracy?

后端 未结 16 1431
忘掉有多难
忘掉有多难 2020-11-22 08:22

Which is better to use for timing in Python? time.clock() or time.time()? Which one provides more accuracy?

for example:

start = time.clock()
... do          


        
16条回答
  •  隐瞒了意图╮
    2020-11-22 08:46

    time.clock() was removed in Python 3.8 because it had platform-dependent behavior:

    • On Unix, return the current processor time as a floating point number expressed in seconds.
    • On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number

      print(time.clock()); time.sleep(10); print(time.clock())
      # Linux  :  0.0382  0.0384   # see Processor Time
      # Windows: 26.1224 36.1566   # see Wall-Clock Time
      

    So which function to pick instead?

    • Processor Time: This is how long this specific process spends actively being executed on the CPU. Sleep, waiting for a web request, or time when only other processes are executed will not contribute to this.

      • Use time.process_time()
    • Wall-Clock Time: This refers to how much time has passed "on a clock hanging on the wall", i.e. outside real time.

      • Use time.perf_counter()

        • time.time() also measures wall-clock time but can be reset, so you could go back in time
        • time.monotonic() cannot be reset (monotonic = only goes forward) but has lower precision than time.perf_counter()

提交回复
热议问题