estimate-complexity

估算 PHP 代码中的算法复杂度。分析时间和空间复杂度,检测 O(n²)、指数增长或低效数据结构等性能问题。

仓库最近推送
GitHub Stars
109
Forks
26
Issues / PRs
1

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "estimate-complexity":https://skillpi.com/zh/skills/deepskill-49865fa51f3bbbbb6b572483332b552ffd65194f4ab6dec87c9790aa4ec26755。安装前核对上游来源和版本:https://github.com/dykyi-roman/awesome-claude-code。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

估算 PHP 代码中的算法复杂度。分析时间和空间复杂度,检测 O(n²)、指数增长或低效数据结构等性能问题。

0 下载

介绍来源: third_party · dykyi-roman · 0.0.1 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
输入和输出
减记
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: estimate-complexity
description: Estimates algorithm complexity in PHP code. Analyzes time and space complexity, detects O(n²) algorithms, exponential growth patterns, inefficient data structures.

Algorithm Complexity Estimation

Analyze PHP code to estimate time and space complexity.

Complexity Patterns

1. O(n²) Algorithms

// O(n²): Nested loop over same collection
foreach ($items as $i => $item1) {
    foreach ($items as $j => $item2) {
        if ($i !== $j && $item1->matches($item2)) {
            // Comparison
        }
    }
}

// O(n²): Array operations in loop
$result = [];
foreach ($items as $item) {
    if (!in_array($item, $result)) { // O(n) search
        $result[] = $item;
    }
}

// O(n): Using hash set
$seen = [];
$result = [];
foreach ($items as $item) {
    $key = $item->getKey();
    if (!isset($seen[$key])) {
        $seen[$key] = true;
        $result[] = $item;
    }
}

2. Exponential Growth O(2^n)

// O(2^n): Naive Fibonacci
function fib(int $n): int {
    if ($n <= 1) return $n;
    return fib($n - 1) + fib($n - 2);
}

// O(n): Memoized
function fibMemo(int $n, array &$memo = []): int {
    if ($n <= 1) return $n;
    if (!isset($memo[$n])) {
        $memo[$n] = fibMemo($n - 1, $memo) + fibMemo($n - 2, $memo);
    }
    return $memo[$n];
}

// O(2^n): Subsets generation
function subsets(array $set): array {
    if (empty($set)) return [[]];
    $first = array_shift($set);
    $rest = subsets($set);
    $withFirst = array_map(fn($s) => array_merge([$first], $s), $rest);
    return array_merge($rest, $withFirst);
}

3. O(n!) Factorial

// O(n!): Permutations
function permute(array $arr): array {
    if (count($arr) <= 1) return [$arr];
    $perms = [];
    foreach ($arr as $i => $item) {
        $rest = array_values(array_diff_key($arr, [$i => true]));
        foreach (permute($rest) as $perm) {
            $perms[] = array_merge([$item], $perm);
        }
    }
    return $perms;
}

4. Inefficient String Operations

// NOT quadratic: `.=` is amortised O(1) in PHP
$result = '';
foreach ($lines as $line) {
    $result .= $line; // realloc in place while refcount === 1
}
// Total: O(total output length). Do NOT report this as O(n²).

// O(n²): concatenation that COPIES on every iteration
$result = '';
foreach ($lines as $line) {
    $result = $result . $line;      // same, still amortised O(1)
    $log[] = $result;               // ← THIS is the problem: n snapshots of a
                                    //   growing string → O(n²) memory and time
}

// O(n²): rebuilding a string through a function that returns a copy
foreach ($lines as $line) {
    $result = str_replace('a', 'b', $result . $line); // full re-scan each pass
}

Rule: .= alone is not a complexity smell. Flag it only when each intermediate value is retained, re-scanned, or passed through a string function every iteration.

5. Inefficient Array Operations

// O(n²): array_merge in loop
$result = [];
foreach ($batches as $batch) {
    $result = array_merge($result, $batch); // O(n) each time
}

// O(n): Spread operator
$result = array_merge(...$batches);

// O(n²): array_unshift in loop
$result = [];
foreach ($items as $item) {
    array_unshift($result, $item); // O(n) shift
}

// O(n): Build then reverse
$result = [];
foreach ($items as $item) {
    $result[] = $item;
}
$result = array_reverse($result);

6. Inefficient Search

// O(n): Linear search each time
foreach ($queries as $query) {
    foreach ($items as $item) {
        if ($item->matches($query)) {
            $results[] = $item;
            break;
        }
    }
}
// Total: O(q*n)

// O(q + n): Build index first
$index = [];
foreach ($items as $item) {
    $index[$item->getKey()] = $item;
}
foreach ($queries as $query) {
    if (isset($index[$query])) {
        $results[] = $index[$query];
    }
}

7. Recursive Depth

// O(n) stack depth: Linear recursion
function process(array $items): void {
    if (empty($items)) return;
    $first = array_shift($items);
    handle($first);
    process($items); // Stack depth = n
}

// O(log n) stack depth: Divide and conquer
function processTree(Node $node): void {
    if (!$node) return;
    process($node->value);
    processTree($node->left);
    processTree($node->right);
}

8. Space Complexity

// O(n) space: Building result array
function transform(array $items): array {
    $result = [];
    foreach ($items as $item) {
        $result[] = process($item);
    }
    return $result;
}

// O(1) space: Generator
function transformGenerator(array $items): Generator {
    foreach ($items as $item) {
        yield process($item);
    }
}

// O(n²) space: Matrix
$matrix = [];
for ($i = 0; $i < $n; $i++) {
    $matrix[$i] = array_fill(0, $n, 0);
}

Complexity Quick Reference

Pattern Time Space
Simple loop O(n) O(1)
Nested loop O(n²) O(1)
Binary search O(log n) O(1)
Merge sort O(n log n) O(n)
Hash table lookup O(1) avg O(n)
in_array O(n) O(1)
isset/array key O(1) O(1)

Grep Patterns

These are candidate-narrowing greps — then Read the hit to confirm. A zero result is NOT
proof the code is clean; it usually means the construct spans lines the pattern did not cover.

```bash
# Nested foreach — spans lines, so --multiline is required (no dotall: `.` must not eat newlines)
Grep: "foreach[^\n]*\{[\s\S]{0,400}?foreach" --glob "**/*.php" --multiline

# in_array / array_search inside a loop body (two-pass: find the loop, then Read it)
Grep: "in_array|array_search" --glob "**/*.php"

# array_merge / array_unshift in a loop — genuinely O(n²)
Grep: "array_merge|array_unshift" --glob "**/*.php"

# Recursive function — ripgrep's Rust regex has NO backreferences, so match the
# declaration first and confirm self-recursion by reading the body
Grep: "^\s*(public|private|protected|static|final|\s)*function\s+\w+" --glob "**/*.php"

Not listed on purpose: foreach.*\.=. String concatenation in a loop is amortised O(1) — see section 4. Grepping for it only produces false positives.

Severity Classification

Complexity Dataset Size Severity
O(n²) > 1000 🔴 Critical
O(n²) < 100 🟡 Minor
O(2^n) > 20 🔴 Critical
O(n log n) Any ✅ Acceptable
O(n) Any ✅ Good
O(1) Any ✅ Optimal

Output Format

### Algorithm Complexity: [Description]

**Severity:** 🔴/🟠/🟡
**Location:** `file.php:line`

**Current Complexity:**
- Time: O(n²)
- Space: O(n)

**Issue:**
[Description of the complexity problem]

**Code:**
```php
// Current algorithm

Optimization:

// Optimized algorithm

Optimized Complexity:

  • Time: O(n)
  • Space: O(n)

Performance Impact: For n = 10,000:

  • Before: ~100M operations
  • After: ~10K operations

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值85/100

亮点

  • 面向开发者性能优化需求,提供 PHP 代码算法复杂度分析能力
  • 覆盖时间/空间复杂度、O(n²)、指数增长、低效数据结构等关键场景
  • 具有广泛实用价值和明确受众
触发精准95/100

亮点

  • 触发词精准完整,明确描述核心功能
  • 覆盖多种复杂度模式和边界场景
  • 用户可清晰理解 Skill 适用范围
结构规范90/100

亮点

  • 文档结构清晰,分章节组织内容
  • 提供大量端到端代码示例和优化对比
  • frontmatter 完整,长度适中
执行可靠88/100

待提升项

  • description写错位置 原报告严重程度:轻微

    顶层 frontmatter 中 description 字段为空,实质描述内容位于 skill_body 内部

    改进建议:建议将 description 内容移至顶层 frontmatter 中,以符合规范并提升可读性

亮点

  • 提供具体 grep 模式用于实际代码扫描
  • 复杂度判断逻辑严谨,避免常见误判(如字符串拼接)
  • 输出格式规范,便于集成和结果展示
证据可验 (前四项均值)90/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。