UtilityToolsLab

© 2026 UtilityToolsLab. Built and maintained by the UtilityToolsLab Team.

Free eBooks·About·Changelog·Privacy Policy·Terms of Service·Report a bug
HomeCompetitive ProgrammingStress Tester

Related Tools

Code FormatterMatrix GeneratorComplexity CalcBit VisualizerBitmask PlannerPrime FactorsMEX CalcInterval MergerMatrix RotationPBDS GeneratorSegment TreeGraph VisualizerModulo CalcConvex HullPath FinderOffline JudgeBig-O AnalyzerCombinatoricsDP Table BuilderExtended GCDSieve VisualizerBinary SearchSorting VisualizerSparse Table RMQUnion-Find DSU

CP Stress Tester Generator

Paste your brute force, optimal solution and test generator to get a downloadable Python or Bash stress-test script that finds counter-examples.

You Might Also Like

All Competitive Programming

Code Formatter

Format and beautify C++, Java, and Python code with consistent indentation. 100% client-side — no code leaves your browser.

PBDS Generator

Generate ready-to-paste C++ Order Statistics Tree code. Configure key type, comparator, and duplicate support. One-click copy.

Segment Tree

Input an array, choose sum/min/max/gcd. See the segment tree visualization and get a complete C++ class template to copy.

MEX Calc

Input a comma-separated array and see the MEX (Minimum Excluded) computed step-by-step with frequency table and visual walkthrough.

The bug that survives your own test cases is the one you cannot imagine. Stress testing solves that by generating random inputs, running a slow but obviously correct solution alongside your fast one, and stopping the moment they disagree. The Stress Test Script Generator writes the harness that does it.

Three panes hold the pieces: a brute force in C++, the optimal solution in C++, and a generator in Python. Each arrives with a working skeleton so the shape is clear before you replace it. Set how many iterations to run and the script appears below, compilation commands included.

Nothing is executed here. The output is a script you run locally, which is the only place a C++ compiler exists, and it means your solution source is never transmitted anywhere.

Getting a Counter-Example Out of the Harness

  1. Replace the brute force with something you are certain is correct even if it is exponential. Correctness is the only requirement; speed is explicitly not.
  2. Paste your real solution into the optimal pane. The whole point is that these two disagree, so do not simplify it to make the test pass.
  3. Rewrite the generator to emit constraints small enough that the brute force finishes, typically n of 8 or fewer. A generator producing large cases will look like the optimal solution is fine because you never get past test 3.
  4. Set the iteration count, 200 by default, and choose python or bash for the runner. Python is more portable; bash is shorter and needs no interpreter beyond the shell.
  5. Copy the script, save it beside your source files, and run it. It compiles both programs, loops, and stops at the first mismatch with the failing input printed.

When Not to Use a Stress Test

  • A bug that only appears at the constraint ceiling is invisible here, because the brute force cannot reach that size. A 32-bit overflow that needs n above 100,000 will never fire against a generator capped at 8.
  • If both solutions share a misreading of the problem statement, they agree perfectly and all 200 tests pass. Stress testing checks consistency, not correctness against the actual problem.
  • Problems with multiple valid answers break the equality check. You need a checker that validates the output rather than a diff, and this harness compares text.
  • A generator that never produces the interesting shape will not find the bug. Random arrays rarely contain duplicates, all-equal runs or already-sorted input unless you ask for them.
  • Timing bugs and undefined behaviour can pass all 200 runs and still fail on the judge. A clean sweep raises your confidence by a lot and settles nothing outright.
  • The generator is seeded by the loop counter in the produced script, so a failing iteration is reproducible. Note the number the run stopped on before you start editing.

Generated Stress Test Script (stress_test.py)

#!/usr/bin/env python3
"""
CP Stress Tester — generated by UtilityToolsLab
Finds the first counter-example between brute and optimal solutions.
"""
import subprocess, os, sys, tempfile

MAX_TESTS = 200

BRUTE_CODE = r"""
#include <bits/stdc++.h>
using namespace std;
int main(){
    int n; cin >> n;
    // brute force solution
    cout << n << endl;
}
"""

OPTIMAL_CODE = r"""
#include <bits/stdc++.h>
using namespace std;
int main(){
    int n; cin >> n;
    // optimal solution
    cout << n << endl;
}
"""

GEN_CODE = r"""
import random
import sys

# Generate random test case
n = random.randint(1, 100)
print(n)
"""

def write_file(path, content):
    with open(path, "w") as f:
        f.write(content)

def compile_cpp(src, out):
    result = subprocess.run(
        ["g++", "-O2", "-o", out, src],
        capture_output=True, text=True
    )
    if result.returncode != 0:
        print(f"Compile error:\n{result.stderr}")
        sys.exit(1)

def run_binary(binary, input_data):
    result = subprocess.run(
        [binary], input=input_data, capture_output=True, text=True, timeout=5
    )
    return result.stdout.strip()

def run_gen(gen_script):
    result = subprocess.run(
        [sys.executable, gen_script], capture_output=True, text=True, timeout=5
    )
    return result.stdout

def main():
    tmpdir = tempfile.mkdtemp()
    brute_src  = os.path.join(tmpdir, "brute.cpp")
    opt_src    = os.path.join(tmpdir, "optimal.cpp")
    gen_script = os.path.join(tmpdir, "gen.py")
    brute_bin  = os.path.join(tmpdir, "brute")
    opt_bin    = os.path.join(tmpdir, "optimal")

    print("Compiling brute force...")
    write_file(brute_src, BRUTE_CODE)
    compile_cpp(brute_src, brute_bin)

    print("Compiling optimal solution...")
    write_file(opt_src, OPTIMAL_CODE)
    compile_cpp(opt_src, opt_bin)

    write_file(gen_script, GEN_CODE)

    print(f"Running {MAX_TESTS} stress tests...\n")

    for t in range(1, MAX_TESTS + 1):
        test_input = run_gen(gen_script)
        out_brute  = run_binary(brute_bin,  test_input)
        out_opt    = run_binary(opt_bin,    test_input)

        if out_brute != out_opt:
            print(f"[COUNTER-EXAMPLE FOUND] Test #{t}")
            print(f"--- Input ---\n{test_input}")
            print(f"--- Brute Output ---\n{out_brute}")
            print(f"--- Optimal Output ---\n{out_opt}")
            with open("counter_example.txt", "w") as f:
                f.write(f"Input:\n{test_input}\nBrute:\n{out_brute}\nOptimal:\n{out_opt}")
            print("\nSaved to counter_example.txt")
            return

        if t % 50 == 0:
            print(f"  {t}/{MAX_TESTS} tests passed...")

    print(f"\n✅ All {MAX_TESTS} tests passed — no counter-example found!")

if __name__ == "__main__":
    main()

💡 Run with python3 stress_test.py or bash stress_test.sh — requires g++ and python3 installed locally.