From 59ea2b479ba29bbcdaab19ce0e2206c505494f8c Mon Sep 17 00:00:00 2001 From: zj3D Date: Mon, 10 Mar 2025 13:23:31 +0800 Subject: [PATCH] 01 --- .gitignore | 1 + .vscode/extensions.json | 3 +- C 高性能模式/case_股票分析.md | 48 +++++++++++ C 高性能模式/case_股票分析.py | 109 +++++++++++++++++++++++++ readme.MD | 2 + 5 files changed, 162 insertions(+), 1 deletion(-) create mode 100644 C 高性能模式/case_股票分析.md create mode 100644 C 高性能模式/case_股票分析.py diff --git a/.gitignore b/.gitignore index 1de8013..65f41fd 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ B 高性能模式/log B 高性能模式/test.py .vscode/launch.json .gitignore +.vscode/extensions.json \ No newline at end of file diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 9bf6938..bfc772a 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -2,4 +2,5 @@ "recommendations": [ "bierner.markdown-mermaid" ] -} \ No newline at end of file +} + diff --git a/C 高性能模式/case_股票分析.md b/C 高性能模式/case_股票分析.md new file mode 100644 index 0000000..ee1572b --- /dev/null +++ b/C 高性能模式/case_股票分析.md @@ -0,0 +1,48 @@ + +# 案例研究:股票价格分析 + +## 案例背景 +股票价格分析是金融领域常见任务,涉及从互联网获取实时或历史价格数据(I/O密集型),以及执行复杂计算如傅里叶变换以分析趋势(计算密集型)。 + +## 任务目标 +假设任务是从 Yahoo Finance 获取股票价格数据(如AAPL、MSFT、GOOG),然后对每组数据执行傅里叶变换以分析频率成分。 + +各模型的特点和适用场景说明: + +** 串行执行 ** +特点:顺序执行所有任务, 编程简单。 +性能:作为基准。 +适用场景:任务量少、无性能要求时。 + +** 多线程执行 ** +特点:线程池并发处理 I/O 任务,但受限于 Python 的 GIL(全局解释器锁),计算任务无法并行。 +性能:在 I/O 密集型任务中显著优于串行执行,但在计算密集型任务中提升有限。 +适用场景:网络请求、文件读写等 I/O 密集型任务。 + +** 多进程执行 ** +特点:进程池并行执行任务,可充分利用多核 CPU。 +性能:在计算密集型任务(如傅里叶变换)中表现优异,但在 I/O 任务中因进程开销可能不如多线程或异步。 +适用场景:数学计算、数据处理等计算密集型任务。 + +** 异步执行 ** +特点:单线程处理并发 I/O 任务 。 +性能:在 I/O 密集型任务中效率高,但在计算密集型任务中无优势。 +适用场景:高并发网络请求、API 调用等 I/O 密集型任务。 + +** 混合执行 ** +数据获取使用异步方法,计算部分使用多进程并行。 +结合了异步 I/O 的高效性和多进程计算的并行性。 + +## 性能比较和分析 +多线程和异步在 I/O 密集型任务中大幅缩短时间。 +多进程在计算密集型任务中提升性能。 +运行结果依据实际时间因网络和硬件而异,并不能直接说明执行方式的特点。 +时间消耗测评可以追踪到更细化的步骤进行分析。 + +通过这个案例,读者可以: +理解 I/O 密集型和计算密集型任务的区别, +了解多线程、多进程和异步编程的实现方法。 + + +## 其它 +无代理环境,可以自行查阅资源用 request 直接爬股票数据 。 \ No newline at end of file diff --git a/C 高性能模式/case_股票分析.py b/C 高性能模式/case_股票分析.py new file mode 100644 index 0000000..37b0ffc --- /dev/null +++ b/C 高性能模式/case_股票分析.py @@ -0,0 +1,109 @@ +import yfinance as yf +import numpy as np +from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor +import asyncio +import time +import functools + + +#################################################################### + +# 获取股票数据(I/O密集型任务) +def fetch_stock_data(stock): + print(f"Fetching data for {stock}") + data = yf.download(stock, start="2020-01-01", end="2023-01-01",auto_adjust=False) + return data['Close'].values + + +# 异步获取股票数据 +async def async_fetch_stock_data(stock): + print(f"Fetching data for {stock}") + data = await asyncio.to_thread(yf.download, stock, start="2020-01-01", end="2023-01-01",auto_adjust=False) + return data['Close'].values + + +# 傅里叶变换(计算密集型任务) +def fourier_transform(data): + print("Performing Fourier Transform") + fft_data = np.fft.fft(data) + return np.abs(fft_data) + + +def timeit(message): + def decorator(func): + @functools.wraps(func) + def sync_wrapper(*args, **kwargs): + start_time = time.time() + result = func(*args, **kwargs) + end_time = time.time() + print(f"{message}: {end_time - start_time:.2f} seconds") + return result + async def async_wrapper(*args, **kwargs): + start_time = time.time() + result = await func(*args, **kwargs) + end_time = time.time() + print(f"{message}: {end_time - start_time:.2f} seconds") + return result + if asyncio.iscoroutinefunction(func): + return async_wrapper + else: + return sync_wrapper + return decorator + +#################################################################### + +# 股票列表 +stocks = ['AAPL', 'MSFT', 'GOOG'] + + +# 串行执行 +@timeit("串行执行") +def serial_execution(): + for stock in stocks: + data = fetch_stock_data(stock) + fft_data = fourier_transform(data) + # 可视化(等等...) + + +# 多线程执行(优化 I/O 密集型任务) +@timeit("多线程执行") +def threaded_execution(): + with ThreadPoolExecutor(max_workers=3) as executor: + data_list = list(executor.map(fetch_stock_data, stocks)) + for data in data_list: + fft_data = fourier_transform(data) + # 可视化(等等...) + +# 多进程执行(优化计算密集型任务) +@timeit("多进程执行") +def multiprocessing_execution(): + with ProcessPoolExecutor(max_workers=3) as executor: + data_list = list(executor.map(fetch_stock_data, stocks)) + with ProcessPoolExecutor(max_workers=3) as executor: + fft_data_list = list(executor.map(fourier_transform, data_list)) + # 可视化(等等...) + +# 异步执行(优化 I/O 密集型任务) +@timeit("异步执行") +async def async_execution(): + tasks = [async_fetch_stock_data(stock) for stock in stocks] + data_list = await asyncio.gather(*tasks) + for data in data_list: + fft_data = fourier_transform(data) + # 可视化(等等...) + +@timeit("混合执行") +async def mixed_execution(): + tasks = [async_fetch_stock_data(stock) for stock in stocks] + data_list = await asyncio.gather(*tasks) + with ProcessPoolExecutor(max_workers=3) as executor: + fft_data_list = list(executor.map(fourier_transform, data_list)) + # 可视化(等等...) + + +if __name__ == "__main__": + print("串行执行:"); serial_execution() + print("\n多线程执行:") ; threaded_execution() + print("\n多进程执行:"); multiprocessing_execution() + print("\n异步执行:"); asyncio.run(async_execution()) + print("\n混合执行:") ; asyncio.run(mixed_execution()) \ No newline at end of file diff --git a/readme.MD b/readme.MD index 0fcb323..0e71bda 100644 --- a/readme.MD +++ b/readme.MD @@ -5,8 +5,10 @@ A 代码模式 用一个简单任务,展示各种需求(完成任务简单、可读性强、可复用高、维护成本低等)下的代码写法 + B 面向对象设计模式 用一个业务场景复现面向对象的经典设计模式 + C 高性能模式 考虑执行时间快,内存占用少的一些办法 \ No newline at end of file