from datetime import datetimestart_time = datetime.now()# do your work hereend_time = datetime.now()print('Duration: {}'.format(end_time - start_time))
样本输出例如
Duration: 0:00:08.309267
或
Duration: 1 day, 1:51:24.269711
正如J. F. Sebastian提到的,这种方法可能会遇到一些当地时间的棘手情况,因此使用它更安全:
import datetime as dtimport timeit
class TimingManager(object):"""Context Manager used with the statement 'with' to time some execution.
Example:
with TimingManager() as t:# Code to time"""
clock = timeit.default_timer
def __enter__(self):""""""self.start = self.clock()self.log('\n=> Start Timing: {}')
return self
def __exit__(self, exc_type, exc_val, exc_tb):""""""self.endlog()
return False
def log(self, s, elapsed=None):"""Log current time and elapsed time if present.:param s: Text to display, use '{}' to format the text withthe current time.:param elapsed: Elapsed time to display. Dafault: None, no display."""print s.format(self._secondsToStr(self.clock()))
if(elapsed is not None):print 'Elapsed time: {}\n'.format(elapsed)
def endlog(self):"""Log time for the end of execution with elapsed time."""self.log('=> End Timing: {}', self.now())
def now(self):"""Return current elapsed time as hh:mm:ss string.:return: String."""return str(dt.timedelta(seconds = self.clock() - self.start))
def _secondsToStr(self, sec):"""Convert timestamp to h:mm:ss string.:param sec: Timestamp."""return str(dt.datetime.fromtimestamp(sec))
import time
now = time.time()future = now + 10step = 4 # Why 4 steps? Because until here already four operations executedwhile time.time() < future:step += 3 # Why 3 again? Because a while loop executes one comparison and one plus equal statementstep += 4 # Why 3 more? Because one comparison starting while when time is over plus the final assignment of step + 1 and print statementprint(str(int(step / 10)) + " steps per second")
import timeit
start = timeit.default_timer()
# All the program statementsstop = timeit.default_timer()execution_time = stop - start
print("Program Executed in "+str(execution_time)) # It returns time in seconds
def sample_function(start,**kwargs):try:# Your statementsexcept:# except statements run when your statements raise an exceptionstop = timeit.default_timer()execution_time = stop - startprint("Program executed in " + str(execution_time))
from line_profiler import LineProfilerimport random
def do_stuff(numbers):s = sum(numbers)l = [numbers[i]/43 for i in range(len(numbers))]m = ['hello'+str(numbers[i]) for i in range(len(numbers))]
numbers = [random.randint(1,100) for i in range(1000)]lp = LineProfiler()lp_wrapper = lp(do_stuff)lp_wrapper(numbers)lp.print_stats()
结果将是:
Timer unit: 1e-06 s
Total time: 0.000649 sFile: <ipython-input-2-2e060b054fea>Function: do_stuff at line 4
Line # Hits Time Per Hit % Time Line Contents==============================================================4 def do_stuff(numbers):5 1 10 10.0 1.5 s = sum(numbers)6 1 186 186.0 28.7 l = [numbers[i]/43 for i in range(len(numbers))]7 1 453 453.0 69.8 m = ['hello'+str(numbers[i]) for i in range(len(numbers))]
# Convert your notebook to a .py script:!jupyter nbconvert --to script example_notebook.ipynb
# Run the example_notebook with -t flag for time%run -t example_notebook
产出
IPython CPU timings (estimated):User : 0.00 s.System : 0.00 s.Wall time: 0.00 s.
import time
start = time.localtime()end = time.localtime()"""Total execution time in minutes$ """print(end.tm_min - start.tm_min)"""Total execution time in seconds$ """print(end.tm_sec - start.tm_sec)
#Sample input for a number 20#Sample output [2, 3, 5, 7, 11, 13, 17, 19]#Total Running time = 0.634 seconds
import time
start_time = time.time()
#Method 1 to find all the prime numbers <= a Number
# Function to check whether a number is prime or not.def prime_no(num):if num<2:return Falseelse:for i in range(2, num//2+1):if num % i == 0:return Falsereturn True
#To print all the values <= ndef Prime_under_num(n):a = [2]if n <2:print("None")elif n==2:print(2)else:"Neglecting all even numbers as even numbers won't be prime in order to reduce the time complexity."for i in range(3, n+1, 2):if prime_no(i):a.append(i)print(a)
"When Method 1 is only used outputs of running time for different inputs"#Total Running time = 2.73761 seconds #n = 100#Total Running time = 3.14781 seconds #n = 1000#Total Running time = 8.69278 seconds #n = 10000#Total Running time = 18.73701 seconds #n = 100000
#Method 2 to find all the prime numbers <= a Number
def Prime_under_num(n):a = [2]if n <2:print("None")elif n==2:print(2)else:for i in range(3, n+1, 2):if n%i ==0:passelse:a.append(i)print(a)
"When Method 2 is only used outputs of running time for different inputs"# Total Running time = 2.75935 seconds #n = 100# Total Running time = 2.86332 seconds #n = 1000# Total Running time = 4.59884 seconds #n = 10000# Total Running time = 8.55057 seconds #n = 100000
if __name__ == "__main__" :n = int(input())Prime_under_num(n)print("Total Running time = {:.5f} seconds".format(time.time() - start_time))
if __name__ == "__main__" :n = int(input())start_time = time.time()Prime_under_num(n)print("Total Running time = {:.3f} seconds".format(time.time() - start_time))
因此,当单独使用时,这两种方法的输出如下:-
# Method 1
# Total Running time = 0.00159 seconds #n = 100# Total Running time = 0.00506 seconds #n = 1000# Total Running time = 0.22987 seconds #n = 10000# Total Running time = 18.55819 seconds #n = 100000
# Method 2
# Total Running time = 0.00011 seconds #n = 100# Total Running time = 0.00118 seconds #n = 1000# Total Running time = 0.00302 seconds #n = 10000# Total Running time = 0.01450 seconds #n = 100000