Time.time() use as a timer

11.6 seconds to list 8 files seems too long?

#! /usr/bin/python3.6
# 
# Time how long a section takes to execute
# /home/andy/Downloads has 8 files
Time to list files in directory:
11.606783628463745

import math 
import os
import time
 
our_list = list(range(10000000))
element = 7000000
 
start = time.time()
# This is code we want to time
        
dir = input("Enter directory name: ")

# Read the content of the file
files = os.listdir(dir)

# Print the content of the directory
for file in files:
    print(file)        

print("Time to list files in directory:") 
end = time.time()
 
print(end - start)

Yes. But if you want to make it shorter you have to type faster :slightly_smiling_face:; you are also measuring how long it takes you to type the directory name. start = time.time() is before you ask for the directory name.

3 Likes

I see your point. :slight_smile:

After moving start = time.time(), I get 0.0001838207244873047.

Tip: time.time() might not be the best, and certainly isn’t the only, way to measure the time it takes for something. Check out time.clock_gettime() and the available clock IDs - for starters, you probably want to use a monotonic clock to ensure that a time-of-day adjustment won’t change things, and secondly, you could consider using a dedicated profiling timer (depending on what you’re doing).

2 Likes

Thanks.

What do you think of using time.process_time()?

src= r'/media/storagedrive/Ubuntu_Mate_18.04/COSTA RICA IN 4K.mp4.zip'
dst = r'/home/andy/Downloads/COSTA RICA IN 4K.mp4.zip'

# get the start time
st = time.process_time()
      
# main program

shutil.copyfile(src, dst)

# get the end time
et = time.process_time()

# get execution time
res = et - st
print('CPU Execution time:', res, 'seconds')

process_time() measues the CPU time used not the elapsed time.

What is it you are interested in knowing?

2 Likes

Check the docs for the exact function you’re calling, and decide what it is you actually want to know. “Process time” is how much CPU time your process consumes, and for copying a file, that’s normally not going to be much; but if you want to compare different ways of copying files, to figure out which ones are more CPU efficient, then that would be the perfect tool.

Know what you’re measuring before you measure it :slight_smile:

2 Likes

Also look at the timeit module for timing snippets, including functions.

3 Likes