Thursday 6 May 2021

Python中time.perf_counter模块的简单用法

 终于貌似把第一个工作任务取得了实质性进展!也有心情把这篇文章补上.


工作中碰到了time.perf_counter这个方法,网上只查到很少的信息,


中文简介如下,其实就是对官方文档的一个翻译,也没看到具体用法


time.perf_counter()


返回性能计数器的值(以分秒为单位),即具有最高可用分辨率的时钟,以测量短持续时间。它包括在睡眠期间和系统范围内流逝的时间。返回值的参考点未定义,因此只有连续调用结果之间的差异有效。


https://www.rddoc.com/doc/Python/3.6.0/zh/library/time/


所以自己看了看代码又写了几行代码测试下,感觉这个函数就是个计时器


import time

def func():

    time.sleep(1)

    a=time.perf_counter()#第一次调用per_counter,所以a值应该为零,但是他不是刚好为零

    print(a)

    print(round(a))#把a四舍五入验证下

    print(type(a))#验证a是浮点数

    time.sleep(5)

    b=time.perf_counter()#sleep5秒后,b的值就应该是5

    print(b)

func()

运行结果:




 


perf_counter还有一个特点,就是如果函数1中调用了函数2,函数2中先调用了perf_counter,那么perf_counter的第一次计数就是从函数2中的调用算起.


我有写了个函数2:




然后改写函数1,调用函数2,


import time

from per_counter2 import func2

def func():

    func2()#func2先执行了一次per_counter,所以下面代码的调用从第二次调用开始

    time.sleep(1)

    a=time.perf_counter()#因为上面func2已经调用过一次per_counter,所以a此时应该等于1,不在是0

    print(a)

    print(round(a))#把a四舍五入验证下

    print(type(a))#验证a是浮点数

    time.sleep(5)

    b=time.perf_counter()

    print(b)

func()

执行结果:





点赞

17


评论

3


分享


收藏

16


举报

关注

一键三连


Python——time模块

时光·漫步的博客

 3万+

三种时间格式转化     1. time() 函数 time( )函数用于返回当前时间的时间戳(从1970年1月1日00时00分00秒到现在的浮点秒数) time()函数的语法如下:         time.time()   1、此语法中第一个 time 表示 time 模块,该函数不需要传递参数 2、返回值:返回当前时间的时间戳   >>> import ti...

python——Counter()方法的用法

他说少年如歌

 1万+

详细内容请参考下面的这篇文章: http://www.cnblogs.com/Eva-J/articles/7291842.html




SkYe231_:你好。我复制代码在本地运行,a的输出值为1,b的输出值为6。

import time

def func():

    time.sleep(1)

    a = time.perf_counter()

    print(a)#a的值接近1

    time.sleep(5)

    b = time.perf_counter()

    print(b)#b的值接近6

    print(b-a)#b-a的值接近5

然后我尝试删除a前面的sleep语句,验证一下我的猜想:time.perf_count()是返回程序开始运行到调用这个语句所经历的时间。

import time

def run():

    a = time.perf_counter()

    print(a)#a的值接近0

    time.sleep(5)

    b = time.perf_counter()

    print(b)#b的值接近5

    print(b-a)#b-a的值接近5

————————————————

版权声明:本文为CSDN博主「wangjinyu124419」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/u011519550/article/details/83413318


from : https://blog.csdn.net/u011519550/article/details/83413318

No comments:

Post a Comment