Skip to content

Quickstart

In this guide, you will use Alnoms to detect a "Silent Trap"β€”a common \(O(N^2)\) bottleneck that looks harmless but fails at scale.

1. πŸ“ Create a Target Script

Save the following code as slow_script.py. This function checks for duplicates using an inefficient nested lookup.

"""Inefficient script used for the Alnoms demonstration."""

def slow_membership_sum(arr):
    total = 0
    for x in arr:
        # Intentional O(N^2) membership trap
        if x in arr:
            total += x
    return total

# Required for empirical scaling
def data_gen(n):
    return (list(range(n)),)

if __name__ == "__main__":
    data = list(range(200))
    print(slow_membership_sum(data))

2. ⚑ Run the Audit

Execute a deep performance audit using the CLI:

alnoms analyze slow_script.py --deep --start-n 50 --rounds 4

3. πŸ” Read the Report

Alnoms will generate a comprehensive Performance Report. Review the following key diagnostic signals:

  • 🧠 Detected Intent: The engine identifies the specific algorithmic pattern, such as a Membership test ('in arr') inside loop.
  • 🚨 Static Analysis: Alnoms pinpoints the exact file and line number, explaining why the pattern is inefficient (e.g., \(O(N)\) lookups inside a loop) and providing a Suggested Fix.
  • πŸ“ˆ Empirical Scaling Analysis: The engine performs a doubling test to calculate the Scaling Ratio. A ratio near 4.0 confirms an Est. Complexity of \(O(N^2)\).
  • βš–οΈ Verdict: A final performance grade is issued (e.g., WARNING: Function operates at O(N^2)), indicating if the code is safe for production scale.
  • πŸš€ Expected Impact: The report estimates the tangible performance gainβ€”often 100×–1000Γ—β€”achieved by shifting from quadratic to linear complexity.
  • πŸ” After Optimization (Simulated): Alnoms provides the specific high-performance implementation, such as using alnoms.dsa.structures.separate_chaining_hash_st, to achieve \(O(N)\) scaling.
==================================================
βš–οΈ PERFORMANCE REPORT
==================================================
File: examples/alnoms/scripts/slow_script.py
Timestamp (UTC): 2026-04-20T21:24:34.294600Z
Total Execution Time: 0.0035s

🧠 DETECTED INTENT:
   Membership test ('in arr') inside loop

🚨 STATIC ANALYSIS (Diagnostics & Suggestions)
--------------------------------------------------
1. ⚠️ ISSUE: Membership test ('in arr') inside loop (Function: slow_membership_sum | Line: 7)
   πŸ“– Explanation: Membership checks on lists inside loops are O(N). Convert to a set for O(1) lookups.
   πŸ’Š RECOMMENDED OPTIMIZATION: O(N)
   πŸ—οΈ IMPLEMENTATION: alnoms.dsa.structures.separate_chaining_hash_st
   πŸ” ACCESS TIER: OSS
   ⏱️ Complexity Shift: O(N*M) β†’ O(N + M)

   πŸ’‘ SUGGESTED FIX:
   --- BEFORE ---
   |  for k in keys:
   |      if k in items:
   |          process(k)
   --- AFTER ---
   |  items_set = set(items)
   |  for k in keys:
   |      if k in items_set:
   |          process(k)

⏱️ DYNAMIC PROFILING (Top Execution Bottlenecks)
--------------------------------------------------
   1. slow_membership_sum() -> 7e-05s (2.15%)

πŸ“ˆ EMPIRICAL SCALING ANALYSIS: slow_membership_sum()
--------------------------------------------------
N          | Time (s)     | Ratio    | Est. Complexity
--------------------------------------------------
50         | 0.00001      | -        | Initial Round  
100        | 0.00002      | 3.32     | O(N^2)         
200        | 0.00008      | 3.91     | O(N^2)         
400        | 0.00028      | 3.59     | O(N^2)         

βš–οΈ VERDICT:
⚠️ WARNING: Function operates at O(N^2). May not scale efficiently.

πŸ“Œ CONTEXT
--------------------------------------------------
   Empirical scaling validates asymptotic behavior under increasing load.

πŸš€ EXPECTED IMPACT
--------------------------------------------------
   For N = 10,000:
     β€’ O(NΒ²) β†’ ~100,000,000 operations
     β€’ O(N)  β†’ ~10,000 operations
   Estimated improvement: 100×–1000Γ— depending on workload.

πŸ€– CONFIDENCE
--------------------------------------------------
   High β€” static and empirical signals agree.

πŸ” AFTER OPTIMIZATION (SIMULATED)
--------------------------------------------------
   Expected Complexity: O(N)
   Behavior: Linear scaling with stable performance.
   Suggested Implementation:
       s = set(arr)
       for x in arr:
           if x in s:
               total += x

==================================================

4. 🧐 Understanding the Ratios

The core of Alnoms’ intelligence lies in the Empirical Scaling Ratio. The engine calculates how much longer a function takes to execute when the input size \(N\) is doubled:

Big O Complexity Chart

Visualizing the divergence of linear, quadratic, and cubic growth.

  • Ratio \(2.0\): Linear scaling \(O(N)\). The execution time doubles with the data.
  • Ratio \(4.0\): Quadratic scaling \(O(N^2)\). The execution time quadruples, indicating a nested loop or redundant scan.
  • Ratio \(8.0\): Cubic scaling \(O(N^3)\). Serious structural bottleneck, often involving triple-nested logic.

5. πŸ› οΈ Apply the Fix

Alnoms doesn't just diagnose; it provides the Sovereign Implementation. In the example above, the engine recommended alnoms.dsa.structures.separate_chaining_hash_st.

To apply this professionally, refactor your code to use the Alnoms high-performance structure:

from alnoms.dsa.structures import SeparateChainingHashST

def fast_membership_sum(arr):
    # Convert list to an optimized hash structure
    st = SeparateChainingHashST()
    for item in arr:
        st.put(item, item)

    total = 0
    for x in arr:
        # O(1) lookup vs original O(N)
        if st.contains(x):
            total += x
    return total

# Required for empirical scaling
def data_gen(n):
    return (list(range(n)),)

if __name__ == "__main__":
    data = list(range(200))
    print(fast_membership_sum(data))

6. πŸ” Re-run the Audit

Execute a deep performance audit using the CLI:

alnoms analyze fast_script.py --deep --start-n 50 --rounds 4

7. ⭐ Observe the Improvement

The report now validates that the scaling is linear.

==================================================
βš–οΈ PERFORMANCE REPORT
==================================================
File: examples/alnoms/scripts/fast_script.py
Timestamp (UTC): 2026-04-21T01:28:14.001488Z
Total Execution Time: 0.0106s

🧠 DETECTED INTENT:
   Potentially expensive call 'put()' inside loop

🚨 STATIC ANALYSIS (Diagnostics & Suggestions)
--------------------------------------------------
1. ⚠️ ISSUE: Potentially expensive call 'put()' inside loop (Function: fast_membership_sum | Line: 8)
   πŸ“– Explanation: A costly function call is executed repeatedly. Cache/memoize the result or hoist it outside the loop.
   πŸ’Š RECOMMENDED OPTIMIZATION: O(N)
   πŸ—οΈ IMPLEMENTATION: functools.lru_cache
   πŸ” ACCESS TIER: OSS
   ⏱️ Complexity Shift: O(N * C) β†’ O(N + unique(C))

   πŸ’‘ SUGGESTED FIX:
   --- BEFORE ---
   |  for item in items:
   |      value = expensive_fn(item)
   |      process(value)
   --- AFTER ---
   |  cache = {}
   |  for item in items:
   |      if item not in cache:
   |          cache[item] = expensive_fn(item)
   |      process(cache[item])

⏱️ DYNAMIC PROFILING (Top Execution Bottlenecks)
--------------------------------------------------
   1. fast_membership_sum() -> 0.00041s (3.89%)

πŸ“ˆ EMPIRICAL SCALING ANALYSIS: fast_membership_sum()
--------------------------------------------------
N          | Time (s)     | Ratio    | Est. Complexity
--------------------------------------------------
50         | 0.00006      | -        | Initial Round  
100        | 0.00009      | 1.43     | O(N)           
200        | 0.00014      | 1.66     | O(N)           
400        | 0.00026      | 1.83     | O(N)           

βš–οΈ VERDICT:
βœ… PASSED: Function operates at O(N). Safe for scaling.

πŸ“Œ CONTEXT
--------------------------------------------------
   Empirical scaling validates asymptotic behavior under increasing load.

πŸš€ EXPECTED IMPACT
--------------------------------------------------
   For N = 10,000:
     β€’ O(NΒ²) β†’ ~100,000,000 operations
     β€’ O(N)  β†’ ~10,000 operations
   Estimated improvement: 100×–1000Γ— depending on workload.

πŸ€– CONFIDENCE
--------------------------------------------------
   Medium β€” mixed signals between analysis methods.

πŸ” AFTER OPTIMIZATION (SIMULATED)
--------------------------------------------------
   Expected Complexity: O(N)
   Behavior: Linear scaling with stable performance.
   Suggested Implementation:
       s = set(arr)
       for x in arr:
           if x in s:
               total += x

==================================================

▢️ Next Steps

Now that you have executed your first audit: