Я запускаю код, который выполняет векторизованные вычисления с использованием подхода ленивых полярностей. Код повторяется примерно 4000 раз, и его выполнение занимает около 4 секунд. Однако, когда я проверяю загрузку ЦП, я вижу, что используется только 25% ЦП. Я хотел бы увеличить загрузку ЦП до 80–100%.
Я запускаю это на своем компьютере под управлением Windows. Ниже приведен пример класса условий, в котором функция оценки выполняется каждый раз в цикле. Как я могу изменить код или конфигурацию, чтобы обеспечить использование большего количества ресурсов ЦП?
from src.conditions.base_condition import BaseCondition
import polars as pl
from src.utils.types import TimeFrameDataFrames
from src.enums.types_enums import TimeFrame
short_avg_period_options = [20, 30, 40, 50]
long_avg_period_options = [100, 140, 160, 200]
class MovingAverageCondition(BaseCondition):
def __init__(self, short_avg_period: int = 20, long_avg_period: int = 200, bullish: bool = True, timeframe: TimeFrame = TimeFrame.M5):
self.short_avg_period = short_avg_period
self.long_avg_period = long_avg_period
self.bullish = bullish
self.timeframe = timeframe
@property
def name(self) -> str:
return 'MovingAverageCondition'
def get_parameters(self) -> dict:
return {
'short_avg_period': self.short_avg_period,
'long_avg_period': self.long_avg_period,
'bullish': self.bullish,
'timeframe': self.timeframe
}
def required_timeframes(self) -> list:
return [self.timeframe]
def evaluate(self, dfs: TimeFrameDataFrames, **kwargs) -> pl.Series:
"""
Evaluates the condition using Polars DataFrame from the specified timeframe.
Returns a Polars Series indicating where the condition is met.
"""
timeframe_df = dfs.get(self.timeframe)
if timeframe_df is None:
raise ValueError(f"{self.timeframe.value} data is required for MovingAverageCondition.")
# Use lazy evaluation for performance optimization
timeframe_df_lazy = timeframe_df.lazy()
# Calculate short and long moving averages (lazy)
sma_short = pl.col('Close').rolling_mean(window_size=self.short_avg_period)
sma_long = pl.col('Close').rolling_mean(window_size=self.long_avg_period)
# Bullish or bearish condition check (lazy)
if self.bullish:
condition = (pl.col('Close') > sma_short) & (sma_short > sma_long)
else:
condition = (pl.col('Close') < sma_short) & (sma_short < sma_long)
# Collect the result and fill any null values
result_df = timeframe_df_lazy.select(condition.alias("condition")).collect()
return result_df["condition"].fill_null(False)
@staticmethod
def get_instances():
instances = []
for short in short_avg_period_options:
for long in long_avg_period_options:
instances.append(MovingAverageCondition(short_avg_period=short, long_avg_period=long))
return instances
import os
import psutil
import polars as pl
import time
class TrackPerformance:
@staticmethod
def track_cpu_usage(func):
# Measure CPU usage during Polars execution
cpu_usage_before = psutil.cpu_percent(interval=None)
start_time = time.time()
# Execute your Polars operation here (example)
func()
end_time = time.time()
cpu_usage_after = psutil.cpu_percent(interval=None)
print(f"CPU usage before: {cpu_usage_before}%")
print(f"CPU usage after: {cpu_usage_after}%")
print(f"Execution time: {end_time - start_time:.4f} seconds")
Подробнее здесь: https://stackoverflow.com/questions/790 ... ilable-cpu