import requestsimport timefor i inrange(10): response = requests.get('http://example.com')print(response.status_code) time.sleep(1)# Wait for 1 second before the next request
PYTHON
import timedefmy_func():print("Function executed")whileTrue:my_func() time.sleep(0.5)# Wait for 1 seconds before running the function again
執行結果:
Function executed
Function executed
Function executed
Function executed
...
範例 – 倒數計時器
PYTHON
import timedefcountdown(t):while t: mins, secs =divmod(t, 60) timer ='{:02d}:{:02d}'.format(mins, secs)print(timer, end="\r") time.sleep(1) t -=1print('Countdown over!')# start countdown of 10 secondscountdown(20)
PYTHON
import timeclassCountdown:def__init__(self,hours=0,minutes=0,seconds=0): self.hours = hours self.minutes = minutes self.seconds = secondsdefconvert_seconds(self): total_seconds = self.hours *3600+ self.minutes *60+ self.secondsreturn total_secondsdefcountdown(self): t = self.convert_seconds()while t: hours, remainder =divmod(t, 3600)# Calculate hours minutes, seconds =divmod(remainder, 60)# Calculate other timer ='{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)print(timer, end="\r") time.sleep(1) t -=1print('Countdown over!')# With only secondscountdown_time =Countdown(seconds=90)countdown_time.countdown()# With only minutes and secondscountdown_time =Countdown(minutes=2, seconds=30)countdown_time.countdown()# With hours, minutes and secondscountdown_time =Countdown(hours=0, minutes=1, seconds=30)countdown_time.countdown()
import functoolsimport randomimport timedefmeasure_execution_time(func):''' _is_recursive_call is False by default, so for the top-level call (the one you make directly), the start and end times will be set and the execution time will be printed. For the recursive calls, _is_recursive_call=True, so the start and end times won't be set and the execution time won't be printed. '''@functools.wraps(func)defwrapper(*args,_is_recursive_call=False,**kwargs):ifnot _is_recursive_call: wrapper._start_time = time.perf_counter()# Set the start time only for the top-level call result =func(*args, **kwargs)# Call the functionifnot _is_recursive_call:# If this is the top-level call wrapper._end_time = time.perf_counter()# Set the end timeprint(f"{func.__name__} executed in {wrapper._end_time - wrapper._start_time:.3f} s.")return resultreturn wrapper @measure_execution_timedeffibonacci(n): # Fibonacci sequenceif n <2:return nreturnfibonacci(n-1, _is_recursive_call=True)+fibonacci(n-2, _is_recursive_call=True)@measure_execution_timedefalgorithm1(data):returnsorted(data)@measure_execution_timedefalgorithm2(data):returnlist(set(data))data = [random.randint(0, 100000)for _ inrange(100000)]algorithm1(data)algorithm2(data)fibonacci(20)
import functoolsimport randomimport time# Define debugging decoratordefdebug(func):"""Prints the function signature and return value"""@functools.wraps(func)defwrapper_debug(*args,**kwargs): args_repr = [repr(a)for a in args] kwargs_repr = [f"{k}={v!r}"for k, v in kwargs.items()] signature =", ".join(args_repr + kwargs_repr)print(f"Calling {func.__name__}({signature})") start = time.perf_counter() value =func(*args, **kwargs) end = time.perf_counter()print(f"{func.__name__} returned {value!r} in {end-start:.5f} secs")return valuereturn wrapper_debug@debugdefalgorithm1(data):returnsorted(data)@debugdefalgorithm2(data):returnlist(set(data))data = [random.randint(0, 10)for _ inrange(10)]algorithm1(data)algorithm2(data)