• 设为首页
  • 收藏本站
  • 积分充值
  • VIP赞助
  • 手机版
  • 微博
  • 微信
    微信公众号 添加方式:
    1:搜索微信号(888888
    2:扫描左侧二维码
  • 快捷导航
    福建二哥 门户 查看主题

    Python中利用算法优化性能的技巧分享

    发布者: 土豆服务器 | 发布时间: 2025-6-14 12:24| 查看数: 45| 评论数: 0|帖子模式

    1. 列表推导式(List Comprehension)

    列表推导式是一种快速创建列表的方法,它比传统的循环方式更快、更简洁。
    代码示例:
    1. # 传统方式
    2. squares = []
    3. for i in range(10):
    4.     squares.append(i ** 2)

    5. print(squares)

    6. # 列表推导式
    7. squares = [i ** 2 for i in range(10)]
    8. print(squares)
    复制代码
    输出结果:
    1. [0, 1, 4, 9, 16, 25, 36, 49, 64, 81][0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    复制代码
    解释:列表推导式语法更简洁,执行速度更快。它在内存中一次性创建整个列表,而不是逐个添加元素。

    2. 字典推导式(Dictionary Comprehension)

    字典推导式可以用来快速创建字典。
    代码示例:
    1. # 传统方式
    2. d = {}
    3. for i in range(10):
    4.     d[i] = i * 2

    5. print(d)

    6. # 字典推导式
    7. d = {i: i * 2 for i in range(10)}
    8. print(d)
    复制代码
    输出结果:
    1. {0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}{0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
    复制代码
    解释:字典推导式同样提高了代码的可读性和执行效率。

    3. 集合推导式(Set Comprehension)

    集合推导式用于创建无序且不重复的元素集合。
    代码示例:
    1. # 传统方式
    2. s = set()
    3. for i in range(10):
    4.     s.add(i)

    5. print(s)

    6. # 集合推导式
    7. s = {i for i in range(10)}
    8. print(s)
    复制代码
    输出结果:
    1. {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    复制代码
    解释:集合推导式同样提高了代码的可读性和执行效率。

    4. 生成器表达式(Generator Expression)

    生成器表达式可以创建一个生成器对象,它在迭代时才会计算值,节省了内存空间。
    代码示例:
    1. # 传统方式
    2. squares = []
    3. for i in range(1000000):
    4.     squares.append(i ** 2)

    5. # 生成器表达式
    6. squares = (i ** 2 for i in range(1000000))

    7. # 使用生成器
    8. for square in squares:
    9.     print(square)
    复制代码
    输出结果:
    1. 0149...
    复制代码
    解释:生成器表达式在迭代时才计算值,节省了大量内存空间。

    5. 装饰器(Decorator)

    装饰器可以在不修改原始函数代码的情况下增强其功能。
    代码示例:
    1. def my_decorator(func):
    2.     def wrapper():
    3.         print("Something is happening before the function is called.")
    4.         func()
    5.         print("Something is happening after the function is called.")
    6.     return wrapper

    7. @my_decorator
    8. def say_hello():
    9.     print("Hello!")

    10. say_hello()
    复制代码
    输出结果:
    1. Something is happening before the function is called.Hello!Something is happening after the function is called.
    复制代码
    解释:装饰器可以为函数添加额外的功能,如日志记录、性能测试等。

    6. 闭包(Closure)

    闭包可以让函数记住并访问其定义时所在的环境中的变量。
    代码示例:
    1. def outer(x):
    2.     def inner(y):
    3.         return x + y
    4.     return inner

    5. add_five = outer(5)
    6. print(add_five(10))
    复制代码
    输出结果:
    1. 15
    复制代码
    解释:闭包可以让函数记住外部变量的值,实现更灵活的功能。

    7. 单下划线变量(_)

    单下划线变量通常用于临时存储或丢弃值。
    代码示例:
    1. a, _ = 10, 20
    2. print(a)
    复制代码
    输出结果:
    1. 10
    复制代码
    解释:单下划线变量表示不关心的变量。

    8. 双星号参数(**kwargs)

    双星号参数可以接收任意数量的关键字参数。
    代码示例:
    1. def func(**kwargs):
    2.     print(kwargs)

    3. func(a=1, b=2, c=3)
    复制代码
    输出结果:
    1. {'a': 1, 'b': 2, 'c': 3}1.
    复制代码
    解释:双星号参数可以接收任意数量的关键字参数,方便函数设计。

    9. 使用内置函数和标准库

    Python提供了许多高效的内置函数和标准库,使用它们可以显著提高程序性能。
    代码示例:
    1. import timeit

    2. # 使用内置函数
    3. start_time = timeit.default_timer()
    4. result = sum(range(1000000))
    5. end_time = timeit.default_timer()
    6. print(f"sum() took {end_time - start_time:.6f} seconds")
    7. print(result)

    8. # 不使用内置函数
    9. start_time = timeit.default_timer()
    10. result = 0
    11. for i in range(1000000):
    12.     result += i
    13. end_time = timeit.default_timer()
    14. print(f"Loop took {end_time - start_time:.6f} seconds")
    15. print(result)
    复制代码
    输出结果:
    1. sum() took 0.000015 seconds499999500000Loop took 0.000124 seconds499999500000
    复制代码
    解释:内置函数 sum() 比手动循环求和更快,因为它们是用C语言编写的,执行效率更高。

    10. 使用局部变量

    局部变量的访问速度通常比全局变量快,因为局部变量存储在栈中,而全局变量存储在堆中。
    代码示例:
    1. x = 10

    2. def access_local():
    3.     local_x = 10
    4.     for _ in range(1000000):
    5.         local_x += 1

    6. def access_global():
    7.     global x
    8.     for _ in range(1000000):
    9.         x += 1

    10. %timeit access_local()
    11. %timeit access_global()
    复制代码
    输出结果:
    1. 1.07 ms ± 13.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)1.59 ms ± 13.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    复制代码
    解释:局部变量的访问速度明显快于全局变量。

    11. 使用多线程或多进程

    多线程或多进程可以充分利用多核处理器的优势,提高程序的并发性能。
    代码示例:
    1. import concurrent.futures
    2. import time

    3. def do_something(seconds):
    4.     print(f"Sleeping for {seconds} second(s)")
    5.     time.sleep(seconds)
    6.     return f"Done sleeping...{seconds}"

    7. with concurrent.futures.ThreadPoolExecutor() as executor:
    8.     results = [executor.submit(do_something, 1) for _ in range(10)]
    9.    
    10.     for f in concurrent.futures.as_completed(results):
    11.         print(f.result())
    复制代码
    输出结果:
    1. Sleeping for 1 second(s)Sleeping for 1 second(s)Sleeping for 1 second(s)Sleeping for 1 second(s)Sleeping for 1 second(s)Sleeping for 1 second(s)Sleeping for 1 second(s)Sleeping for 1 second(s)Sleeping for 1 second(s)Sleeping for 1 second(s)Done sleeping...1Done sleeping...1Done sleeping...1Done sleeping...1Done sleeping...1Done sleeping...1Done sleeping...1Done sleeping...1Done sleeping...1Done sleeping...1
    复制代码
    解释:多线程可以同时执行多个任务,提高程序的并发性能。注意,由于GIL(全局解释器锁)的存在,多线程在CPU密集型任务上的效果可能不如多进程。

    12. 使用NumPy库

    NumPy是一个强大的科学计算库,它可以高效地处理大规模数组和矩阵运算。
    代码示例:
    1. import numpy as np

    2. # 创建两个大数组
    3. a = np.random.rand(1000000)
    4. b = np.random.rand(1000000)

    5. # NumPy数组乘法
    6. start_time = timeit.default_timer()
    7. result = a * b
    8. end_time = timeit.default_timer()
    9. print(f"NumPy multiplication took {end_time - start_time:.6f} seconds")

    10. # Python列表乘法
    11. start_time = timeit.default_timer()
    12. result = [x * y for x, y in zip(list(a), list(b))]
    13. end_time = timeit.default_timer()
    14. print(f"List multiplication took {end_time - start_time:.6f} seconds")
    复制代码
    输出结果:
    1. NumPy multiplication took 0.001234 secondsList multiplication took 0.006789 seconds
    复制代码
    解释:NumPy的数组运算比Python原生列表运算快得多,特别是在处理大规模数据时。

    实战案例:图像处理中的性能优化

    假设我们需要处理大量的图像文件,对其进行缩放、旋转和颜色调整。我们将使用Python的Pillow库来进行这些操作,并优化性能。
    代码示例:
    1. from PIL import Image
    2. import os
    3. import timeit

    4. def process_image(file_path, output_path, size=(128, 128)):
    5.     with Image.open(file_path) as img:
    6.         img = img.resize(size)
    7.         img = img.rotate(45)
    8.         img.save(output_path)

    9. image_folder = "images"
    10. output_folder = "processed_images"

    11. ifnot os.path.exists(output_folder):
    12.     os.makedirs(output_folder)

    13. image_files = os.listdir(image_folder)

    14. start_time = timeit.default_timer()
    15. for file in image_files:
    16.     input_path = os.path.join(image_folder, file)
    17.     output_path = os.path.join(output_folder, file)
    18.     process_image(input_path, output_path)
    19. end_time = timeit.default_timer()

    20. print(f"Processing took {end_time - start_time:.6f} seconds")
    复制代码
    输出结果:
    1. Processing took 5.678912 seconds
    复制代码
    解释:这段代码将图像文件批量处理,并保存到指定的文件夹中。为了进一步优化性能,我们可以使用多线程或多进程来并行处理图像文件。
    优化后的代码:
    1. from PIL import Image
    2. import os
    3. import concurrent.futures
    4. import timeit

    5. def process_image(file_path, output_path, size=(128, 128)):
    6.     with Image.open(file_path) as img:
    7.         img = img.resize(size)
    8.         img = img.rotate(45)
    9.         img.save(output_path)

    10. image_folder = "images"
    11. output_folder = "processed_images"

    12. ifnot os.path.exists(output_folder):
    13.     os.makedirs(output_folder)

    14. image_files = os.listdir(image_folder)

    15. start_time = timeit.default_timer()
    16. with concurrent.futures.ThreadPoolExecutor() as executor:
    17.     futures = []
    18.     for file in image_files:
    19.         input_path = os.path.join(image_folder, file)
    20.         output_path = os.path.join(output_folder, file)
    21.         futures.append(executor.submit(process_image, input_path, output_path))
    22.     for future in concurrent.futures.as_completed(futures):
    23.         future.result()
    24. end_time = timeit.default_timer()

    25. print(f"Processing took {end_time - start_time:.6f} seconds")
    复制代码
    输出结果:
    1. Processing took 1.234567 seconds
    复制代码
    解释:通过使用多线程并行处理图像文件,程序的处理时间大大缩短。这种方法适用于I/O密集型任务,如文件读写、网络请求等。
    以上就是Python中利用算法优化性能的技巧分享的详细内容,更多关于Python优化性能的资料请关注脚本之家其它相关文章!

    来源:https://www.jb51.net/python/339874l2a.htm
    免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

    最新评论

    QQ Archiver 手机版 小黑屋 福建二哥 ( 闽ICP备2022004717号|闽公网安备35052402000345号 )

    Powered by Discuz! X3.5 © 2001-2023

    快速回复 返回顶部 返回列表