Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python timeit

import timeit

def list_comprehension():
   """comprehension"""
   l = [i for i in range(10_000)]

def list_range():
   """list range"""
   l = list(range(10_000))

# number of executions to test
expSize = 1000

# time the functions 1000 times
time1 = timeit.timeit(list_comprehension, number=expSize)
time2 = timeit.timeit(list_range, number=expSize)
print("list_comprehension() execution result time", time1)
print("list_range() execution result time", time2)
print("list_comprehension() time divided by func2 time", time1/time2)
# list_comprehension() execution result time 0.14136912487447262
# list_range() execution result time 0.08224983396939933
# list_comprehension() time divided by func2 time 1.718777024243822
# list(range) executes faster than range in a list comprehension

# time the functions 1000 times and store the results in a list after each repeat test
time1 = timeit.repeat(list_comprehension, number=expSize, repeat=3)
time2 = timeit.repeat(list_range, number=expSize, repeat=3)
print("list_comprehension() execution result time", time1)
print("list_range() execution result time", time2)
# list_comprehension() execution result time [0.13349625002592802, 0.13272812496870756, 0.13246491691097617]
# list_range() execution result time [0.08029774995520711, 0.07969208294525743, 0.08046487509272993]

print("-".join(str(n) for n in range(100)))
# output 0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19-20-21-22-23-24-25-26-27-28-29-30...

range_str_joined_time = timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
print(range_str_joined_time)
# output 0.08738012495450675
Source by codefreelance.net #
 
PREVIOUS NEXT
Tagged: #python #timeit
ADD COMMENT
Topic
Name
1+4 =