In [1]:
import timeit
Lets use time it to time various methods of creating the string '0-1-2-3-.....-99'
We'll pass two arguments the actual line we want to test encapsulated as a string and the number of times we wish to run it. Here we'll choose 10,000 runs to get some high enough numbers to compare various methods.
In [2]:
# Using For Loop
timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
Out[2]:
In [3]:
# Using List Comprehension
timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)
Out[3]:
In [4]:
# Using Map Function
timeit.timeit('"-".join(map(str, range(100)))', number=10000)
Out[4]:
It also has a Command-Line Interface
In [ ]:
# $ python3 -m timeit '"-".join(str(n) for n in range(100))'
# 10000 loops, best of 3: 30.2 usec per loop
# $ python3 -m timeit '"-".join([str(n) for n in range(100)])'
# 10000 loops, best of 3: 27.5 usec per loop
# $ python3 -m timeit '"-".join(map(str, range(100)))'
# 10000 loops, best of 3: 23.2 usec per loop
Now lets introduce iPython's magic function %timeit
iPython's %timeit will perform the code in the same line a certain number of times (loops) and will give you the fastest performance time (best of 3).
Lets repeat the above examinations using iPython magic!
In [5]:
%timeit "-".join(str(n) for n in range(100))
In [6]:
%timeit "-".join([str(n) for n in range(100)])
In [7]:
%timeit "-".join(map(str, range(100)))
In [9]:
from datetime import date
now = date.today()
print(now)
In [15]:
now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
Out[15]:
In [16]:
print('ctime:', now.ctime())
print('tuple:', now.timetuple())
print('ordinal:', now.toordinal())
print('Year:', now.year)
print('Mon :', now.month)
print('Day :', now.day)
In [18]:
print('Earliest :', date.min)
print('Latest :', date.max)
print('Resolution:', date.resolution)
In [21]:
d1 = date(2017, 3, 11)
print('d1:', d1)
d2 = d1.replace(year=1997)
print('d2:', d2)
In [30]:
from datetime import time
t = time(5,20,25,100)
print(t)
In [31]:
print('hour :', t.hour)
print('minute:', t.minute)
print('second:', t.second)
print('microsecond:', t.microsecond)
print('tzinfo:', t.tzinfo)
In [33]:
print('Earliest :', time.min)
print('Latest :', time.max)
print('Resolution:', time.resolution)
In [14]:
birthday = date(1971,4,22)
age = now - birthday
age.days
Out[14]:
In [22]:
d1 - d2
Out[22]: