Created
June 13, 2016 12:07
-
-
Save selfboot/67c97f92d4e4d70208d1e592a1bac1da to your computer and use it in GitHub Desktop.
Different ways to check the time cost!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #! /usr/bin/env python | |
| # -*- coding: utf-8 -*- | |
| # @Last Modified time: 2016-06-13 20:00:34 | |
| orignal_str = "Profiling a Python program is doing a dynamic analysis"\ | |
| "that measures the execution time of the program and"\ | |
| "everything that compose it." | |
| exec_times = 100000 | |
| # @profile | |
| def slowest_replace(): | |
| replace_list = [] | |
| for i, char in enumerate(orignal_str): | |
| c = char if char != " " else "-" | |
| replace_list.append(c) | |
| return "".join(replace_list) | |
| # @profile | |
| def slow_replace(): | |
| replace_str = "" | |
| for i, char in enumerate(orignal_str): | |
| c = char if char != " " else "-" | |
| replace_str += c | |
| return replace_str | |
| def fast_replace(): | |
| return "-".join(orignal_str.split()) | |
| def fastest_replace(): | |
| return orignal_str.replace(" ", "-") | |
| def test_equal(): | |
| return slow_replace() == fast_replace() == fastest_replace() == slowest_replace() | |
| def _time_analyze_(func): | |
| from time import clock | |
| start = clock() | |
| for i in range(exec_times): | |
| func() | |
| finish = clock() | |
| print "{:<20}{:10.6} s".format(func.__name__ + ":", finish - start) | |
| def simple_profile(): | |
| print "*" * 40, "\nSimple time analyze" | |
| for fun in [slowest_replace, slow_replace, fast_replace, fastest_replace]: | |
| _time_analyze_(fun) | |
| def _timeit_analyze_(func): | |
| from timeit import Timer | |
| t1 = Timer("%s()" % func.__name__, "from __main__ import %s" % func.__name__) | |
| print "{:<20}{:10.6} s".format(func.__name__ + ":", t1.timeit(exec_times)) | |
| def timeit_profile(): | |
| print "*" * 40, "\nModule timeit analyze" | |
| for fun in [slowest_replace, slow_replace, fast_replace, fastest_replace]: | |
| _timeit_analyze_(fun) | |
| if __name__ == "__main__": | |
| assert(test_equal()) | |
| simple_profile() | |
| timeit_profile() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment