Skip to content

Latest commit

 

History

History
113 lines (89 loc) · 2.43 KB

File metadata and controls

113 lines (89 loc) · 2.43 KB

🔧 Prometheus 项目优化技巧库

数据库优化

1. TimescaleDB hypertable(时序数据专用)

-- 自动按时间分区,查询快 100x
SELECT create_hypertable('prices', 'timestamp');

-- Continuous Aggregate 预计算日K
CREATE MATERIALIZED VIEW daily_candles
WITH (timescaledb.continuous) AS
SELECT 
  time_bucket('1 day', timestamp) as day,
  symbol,
  first(open, timestamp) as open,
  max(high) as high,
  min(low) as low,
  last(close, timestamp) as close
FROM prices
GROUP BY day, symbol;

2. 复合索引策略

# 最常用的查询模式
query.filter(Price.symbol == sym).filter(Price.timeframe == tf).order_by(Price.timestamp.desc())

# 对应的索引
op.create_index('ix_prices_symbol_timeframe_timestamp', 'prices', 
                ['symbol', 'timeframe', 'timestamp'])

Python 性能优化

向量化计算(Pandas/NumPy)

# ❌ 慢:Python 循环
for i in range(len(data)):
    sma += data[i]
sma /= n

# ✅ 快:C 语言底层优化
sma = data.rolling(window=n).mean()

# ✅ 更快:指数移动平均
ema = data.ewm(span=n).mean()  # O(n) vs O(n*w)

连接池配置

# aiohttp 连接池
connector = aiohttp.TCPConnector(
    limit=100,              # 总连接数限制
    limit_per_host=20,      # 单域名限制
    ttl_dns_cache=300,      # DNS 缓存 5分钟
    enable_cleanup_closed=True,
)

前端性能优化

React 渲染优化

// 1. 组件记忆化
const Chart = memo(function Chart({ data }) {
  return <canvas>...</canvas>
})

// 2. 函数记忆化
const handleClick = useCallback(() => {
  doSomething(dep)
}, [dep])

// 3. 值记忆化
const expensiveValue = useMemo(() => {
  return heavyComputation(data)
}, [data])

SWR 数据缓存策略

// 自动刷新 + 缓存 + 重试
const { data, error } = useSWR('/api/prices', fetcher, {
  refreshInterval: 30000,     // 30秒自动刷新
  revalidateOnFocus: true,    // 切回页面时刷新
  errorRetryCount: 3,         // 错误重试3次
})

AI 模型优化

LSTM 训练技巧

# 1. Early Stopping 防止过拟合
early_stop = EarlyStopping(patience=10, restore_best_weights=True)

# 2. Gradient Clipping 防止梯度爆炸
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)

# 3. GPU 内存管理
del model
torch.cuda.empty_cache()

文档版本:v2.0 - 加入 Prometheus 项目经验
最后更新:2026-02-13