python使用技巧

这篇博客介绍了Python中装饰器的使用,特别是在计算函数执行时间方面的应用。同时,展示了tqdm库如何在多线程环境下进行进度条显示,提供了示例代码,包括使用ThreadPoolExecutor执行异步任务并配合tqdm进行进度跟踪。
摘要由CSDN通过智能技术生成

本帖仅用来记录一下用法或者写法,并不讲解,如果大家都更好的用法或者写法,可以留言交流。

# 装饰器
def timespend(func):
    def wrapper(*args, **kwargs):
        start_time = time.perf_counter()
        func()
        end_time = time.perf_counter()
        print("func: {}()  use time:  {} second".format(func.__name__, (end_time - start_time)))
    return wrapper
 
# 用法
直接在函数的定义上面加 @timespend  主函数入口用不了
# tqdm 在多线程下使用姿势
import random
from time import sleep
from concurrent.futures import ThreadPoolExecutor, as_completed
from tqdm import tqdm

def func():
    sleep(random.randint(0,3))

if __name__ == '__main__':
    results = []
    with ThreadPoolExecutor(max_workers=3) as t:
        for _ in range(5):
            results.append(t.submit(func))
        for result in tqdm(as_completed(results), total=len(results), desc=func.__name__):
            pass

> func: 100%|██████████| 5/5 [00:05<00:00,  1.00s/it]

import torch
list_ = [[1,2],[2,3],[4,5]]
list_tensor = torch.tensor(list_)    #shape[3, 2]
# 如果想获取第二维度第一位的数值
two = list_tensor[:,1]     # two结果: tensor([2, 3, 5]) shape[3]
# 如果想获取第二维度第一位的数值,并将第一维度变为单维度
two = list_tensor[:,1:2]  # 或者two = list_tensor[:,1::2]
#two结果:tensor([[2],       shape[3, 1]
#               [3],
#               [5]]) 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kui9702

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值