当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python time.clock()用法及代码示例


Python中的时间模块提供了各种与时间相关的函数。

time.clock()Python中的时间模块方法用于获取当前处理器时间,以秒为单位的浮点数。 As,在时间模块中定义的大多数函数都调用相应的C库函数。time.clock()方法还调用相同名称的C库函数以获取结果。返回的浮点值的精度取决于所调用的C库函数。

注意:从Python 3.3版开始不推荐使用此方法,在3.8版中将删除该方法。此方法的行为取决于平台。


用法: time.clock()

参数:不需要任何参数。

返回类型:此方法返回一个浮点值,该值代表以秒为单位的当前处理器时间。

代码1:用于time.clock()获取当前处理器时间的方法

# Python program to explain time.clock() method 
  
# importing time module 
import time 
  
# Get the current processor 
# time in seconds 
pro_time = time.clock() 
  
# print the current  
# processor time 
print("Current processor time (in seconds):", pro_time)
输出:
Current processor time (in seconds): 0.042379

代码2:用于time.clock()获取当前处理器时间的方法

# Python program to explain time.clock() method  
  
# importing time module  
import time  
  
  
# Function to calculate factorial  
# of the given number  
def factorial(n):  
    f = 1
    for i in range(n, 1, -1):  
        f = f * i  
      
    return f  
  
  
# Get the current processor time 
# in seconds at the  
# beginning of the calculation  
# using time.clock() method  
start = time.clock()  
  
# print the processor time in seconds  
print("At the beginning of the calculation")  
print("Processor time (in seconds):", start, "\n")  
  
  
# Calculate factorial of all  
# numbers form 0 to 9  
i = 0
fact = [0] * 10;  
  
while i < 10:  
    fact[i] = factorial(i)  
    i = i + 1
  
# Print the calculated factorial  
for i in range(0, len(fact)):  
    print("Factorial of % d:" % i, fact[i])  
  
# Get the processor time 
# in seconds at the end  
# of the calculation  
# using time.clock() method  
end = time.clock()  
  
print("\nAt the end of the calculation")  
print("Processor time (in seconds):", end)  
print("Time elapsed during the calculation:", end - start)     
输出:
At the beginning of the calculation
Processor time (in seconds): 0.03451 

Factorial of  0: 1
Factorial of  1: 1
Factorial of  2: 2
Factorial of  3: 6
Factorial of  4: 24
Factorial of  5: 120
Factorial of  6: 720
Factorial of  7: 5040
Factorial of  8: 40320
Factorial of  9: 362880

At the end of the calculation
Processor time (in seconds): 0.034715
Time elapsed during the calculation: 0.0002050000000000038

参考: https://docs.python.org/3/library/time.html#time.clock



相关用法


注:本文由纯净天空筛选整理自ihritik大神的英文原创作品 Python | time.clock() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。