当前位置: 首页 > news >正文

【cursor实战】分析python下并行、串行计算性能

提示语

写一个Python并行计算、串行计算性能对比的代码。并行计算要包括多线程和多进程两种,计算的内容要比较复杂

模型

claude-4-sonnet

生成的代码

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Python并行计算与串行计算性能对比程序
包含串行计算、多线程和多进程三种实现方式
使用素数计算作为复杂计算任务
"""import time
import threading
import multiprocessing
import math
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import randomtry:import numpy as npHAS_NUMPY = True
except ImportError:HAS_NUMPY = Falseprint("警告: 未安装numpy,将使用替代方案。运行 'pip install numpy' 以获得完整功能。")def is_prime(n):"""判断一个数是否为素数的复杂算法这里使用稍微复杂一点的算法来增加计算复杂度"""if n < 2:return Falseif n == 2:return Trueif n % 2 == 0:return False# 使用更复杂的算法,增加计算负担sqrt_n = int(math.sqrt(n))for i in range(3, sqrt_n + 1, 2):if n % i == 0:return False# 添加一些额外的计算来增加复杂度temp = math.sin(i) * math.cos(i) + math.log(i + 1)if temp < 0:  # 这个条件永远不会满足,只是为了增加计算量continuereturn Truedef complex_calculation(start, end):"""复杂的计算任务:计算指定范围内的素数,并进行额外的数学运算"""primes = []calculations = []for num in range(start, end):if is_prime(num):primes.append(num)# 添加复杂的数学运算calc_result = math.pow(num, 0.5) * math.log(num + 1) + math.sin(num) * math.cos(num)calculations.append(calc_result)# 进行矩阵运算增加复杂度if len(primes) > 1:matrix_size = min(len(primes), 50)  # 限制矩阵大小避免内存问题if HAS_NUMPY:matrix_a = np.random.rand(matrix_size, matrix_size)matrix_b = np.random.rand(matrix_size, matrix_size)matrix_result = np.dot(matrix_a, matrix_b)complexity_factor = np.sum(matrix_result)else:# 不使用numpy的替代矩阵运算matrix_sum = 0for i in range(matrix_size):for j in range(matrix_size):val_a = random.random()val_b = random.random()matrix_sum += val_a * val_b * math.sin(i+j)complexity_factor = matrix_sumelse:complexity_factor = 1return len(primes), sum(calculations
http://www.xdnf.cn/news/1068697.html

相关文章:

  • 【网站内容安全检测】之1:获取网站所有链接sitemap数据
  • 鸿蒙与h5的交互
  • 机器学习01
  • IDEA高效开发指南:JRebel热部署
  • 每日AI资讯速递 | 2025-06-25
  • Django
  • (C++)vector数组相关基础用法(C++教程)(STL库基础教程)
  • 7.Spring框架
  • TensorFlow Lite (TFLite) 和 PyTorch Mobile模型介绍1
  • 什么是功能测试和非功能测试?
  • Azure 托管 Redis 已正式发布
  • 打造属于你的AI智能体,从数据开始 —— 使用 Bright Data MCP+Trae快速构建垂直智能体
  • 【Elasticsearch】es初识,在项目架构中的用途,与mysql和kafka的配合使用,
  • linux安装docker
  • LE AUDIO---Chapter 2. The Bluetooth® LE Audio architecture
  • 记一次AWS 中RDS优化费用使用的案例
  • 【学习笔记】3.3 Decoder-Only PLM
  • 【目标检测】平均精度(AP)与均值平均精度(mAP)计算详解
  • 从数据到决策:UI前端如何利用数字孪生技术提升管理效率?
  • list的使用和模拟实现
  • 探索解析C++ STL中的 list:双向链表的高效实现与迭代器
  • Flutter MobX 响应式原理与实战详解
  • OpenLayers 上传Shapefile文件
  • docker start mysql失败,解决方案
  • 【猜你需要】使用了Git LFS还是无法上传文件?文件过大?
  • 打造丝滑的Android应用:LiveData完全教程
  • 【启发式算法】RRT*算法详细介绍(Python)
  • Oracle 数据库查询:多表查询
  • 测试平台ui自动化demo说明
  • [论文阅读] 人工智能 + 软件工程 | 探秘LLM软件代理:从黑箱决策到透明轨迹分析