关于计时函数python的信息

python如何实现计时?用python实现计时器功能,代码如下:
''' Simple Timing Function.
This function prints out a message with the elapsed time from the
previous call. It works with most Python 2.x platforms. The function
uses a simple trick to store a persistent variable (clock) without
using a global variable.
'''
import time
def dur( op=None, clock=[time.time()] ):
if op != None:
duration = time.time() - clock[0]
print '%s finished. Duration %.6f seconds.' % (op, duration)
clock[0] = time.time()
# Example
if __name__ == '__main__':
import array
dur()# Initialise the timing clock
opt1 = array.array('H')
for i in range(1000):
for n in range(1000):
opt1.append(n)
dur('Array from append')
opt2 = array.array('H')
seq = range(1000)
for i in range(1000):
opt2.extend(seq)
dur('Array from list extend')
opt3 = array.array('H')
seq = array.array('H', range(1000))
for i in range(1000):
opt3.extend(seq)
dur('Array from array extend')
# Output:
# Array from append finished. Duration 0.175320 seconds.
# Array from list extend finished. Duration 0.068974 seconds.
# Array from array extend finished. Duration 0.001394 seconds.
python怎么对列表操作计时python对列表计时的方法:
【关于计时函数python的信息】使用“import”语句导入time包 , 在列表操作之前用time.time函数获取当前时间 , 在列表操作之后 , 再用time.time获取当前时间,用第二次的时间减去第一次的时间就可以了
示例如下:
执行结果如下:
更多Python知识,请关注:Python自学网?。?
提升Python运行速度的5个小技巧pre{overflow-x: auto}
Python 是世界上使用最广泛的编程语言之一 。它是一种解释型高级通用编程语言计时函数python , 具有广泛的用途计时函数python,几乎可以将其用于所有事物 。其以简单的语法、优雅的代码和丰富的第三方库而闻名 。python除了有很多优点外,但在速度上还有一个非常大的缺点 。
虽然Python代码运行缓慢,但可以通过下面分享的5个小技巧提升Python运行速度计时函数python!
首先,定义一个计时函数timeshow,通过简单的装饰,可以打印指定函数的运行时间 。
这个函数在下面的例子中会被多次使用 。
def timeshow(func):from time import timedef newfunc(*arg, **kw):t1 = time()res = func(*arg, **kw)t2 = time()print(f"{func.__name__: 10} : {t2-t1:.6f} sec")return resreturn newfunc@timeshowdef test_it():print("hello pytip")test_it()1. 选择合适的数据结构
使用正确的数据结构对python脚本的运行时间有显着影响 。Python 有四种内置的数据结构:
列表 :List
元组 :Tuple
集合 :Set
字典 :Dictionary
但是,大多数开发人员在所有情况下都使用列表 。这是不正确的做法,应该根据任务使用合适数据结构 。
运行下面的代码,可以看到元组执行简单检索操作的速度比列表快 。其中dis模块反汇编了一个函数的字节码,这有利于查看列表和元组之间的区别 。
import disdef a():data = https://www.04ip.com/post/[1, 2, 3, 4, 5,6,7,8,9,10]x =data[5]return xdef b():data = (1, 2, 3, 4, 5,6,7,8,9,10)x =data[5]return xprint("-----:使用列表的机器码:------")dis.dis(a)print("-----:使用元组的机器码:------")dis.dis(b)
运行输出:
-----:使用列表的机器码:------
3 0 LOAD_CONST 1 (1)
2 LOAD_CONST 2 (2)
4 LOAD_CONST 3 (3)
6 LOAD_CONST 4 (4)
8 LOAD_CONST 5 (5)
10 LOAD_CONST 6 (6)
12 LOAD_CONST 7 (7)
14 LOAD_CONST 8 (8)
16 LOAD_CONST 9 (9)
18 LOAD_CONST 10 (10)

推荐阅读