Skip to content

Add stats: time in the Python interface versus the C engine - #47

Merged
dance858 merged 4 commits into
mainfrom
stats-api
Dec 2, 2026
Merged

dance858 merged 4 commits into
mainfrom
stats-api

Conversation

@dance858

@dance858 dance858 commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

What

prob.stats (and fn.stats for a compiled expression) reports where the time went, split into the Python interface and the C engine.

s = prob.stats            # snapshot, cumulative since the problem was built
print(s)                  # table
s.hessian.python          # seconds outside the engine
s.hessian.engine          # seconds inside the C engine
s.hessian.calls           # real evaluations (cache hits are not calls)
s.python, s.engine        # totals

Rows: build, setup, objective, gradient, constraints, jacobian, hessian. Every row is a Timing(calls, python, engine).

What a log looks like

All output below is copied unedited from one run (Apple M-series, Release build).

The model is written entry by entry, with 20,000 terms in the objective (since #46 this also raises a PerformanceWarning, on stderr):

import numpy as np
import sparsediffpy as sp

n = 20000
x = sp.Variable(n, 1)
objective = x[0] ** 2
for i in range(1, n):
    objective = objective + x[i] ** 2
prob = sp.Problem(objective, [sp.sin(x[0:10]) * x[10:20]])

It is evaluated at 20 points, as a solver would:

u = np.linspace(1.0, 2.0, n)
for k in range(20):
    prob.set_values(u + k)
    prob.objective(); prob.gradient(); prob.constraints(); prob.jacobian()
    prob.hessian(1.0, np.ones(10))

1. The command print(prob.stats) prints this:

                      calls   python (s)   engine (s)
  build expressions                0.104
  setup                            0.055        2.451
  objective              20        0.000        0.014
  gradient               20        0.000        2.638
  constraints            20        0.000        0.000
  jacobian               20        0.000        0.000
  hessian                20        0.000        1.816
  total                            0.159        6.920
                                      2%          98%

2. The command print(prob.stats.hessian) prints this:

Timing(calls=20, python=0.00015050097670510354, engine=1.8161909999999999)

A small compiled expression with its own variable, evaluated once:

y = sp.Variable(3, 1)
fn = sp.compile(sp.exp(y) + 2.0 * y)
y.value = [1.0, 2.0, 3.0]
fn.forward(); fn.jacobian(); fn.hessian(np.ones(3))

3. The command print(fn.stats) prints this:

                      calls  python (us)  engine (us)
  build expressions               26.167
  setup                           93.250        5.000
  forward                 1        2.458        0.000
  jacobian                1        0.708        0.000
  hessian                 1        3.250        0.000
  total                          125.833        5.000
                                     96%           4%

Benchmark problems

Two models from diffengine-paper-benchmarks, with the data from each problem's data.py (make_data, sample_point), single-threaded BLAS as in bench.py, and 100 evaluation points each.

NMF, m, n, k = 200, 200, 5 (2,000 variables, nearly dense Hessian):

A, k = data
m, n = A.shape
X = sp.Variable(m, k)
Y = sp.Variable(k, n)
prob = sp.Problem(sp.sum((A - X @ Y) ** 2))
for _ in range(100):
    prob.set_values(sample_point(data, rng))
    prob.gradient()
    prob.hessian(1.0, [])

4. The command print(prob.stats) prints this:

                      calls  python (ms)  engine (ms)
  build expressions                0.038
  setup                            0.211       34.021
  objective             100        0.054        5.774
  gradient              100        0.208       70.315
  constraints           100        0.061        0.002
  jacobian              100        0.019        0.000
  hessian               100        0.168      477.030
  total                            0.760      587.142
                                      0%         100%

Optimal pricing, n = 20000 products (40,000 variables, 20,000 constraints):

r, kappa, E = data
n = len(r)
delta = sp.Variable(n, 1)
pi = sp.Variable(n, 1)
profit = sp.sum(r * sp.exp(delta + pi) - kappa * sp.exp(delta))
prob = sp.Problem(-profit, [delta - E @ pi])
lam = np.ones(n)
for _ in range(100):
    prob.set_values(sample_point(data, rng))
    prob.gradient()
    prob.jacobian()
    prob.hessian(1.0, lam)

5. The command print(prob.stats) prints this:

                      calls  python (ms)  engine (ms)
  build expressions                0.033
  setup                            0.700        4.456
  objective             100        0.015        6.859
  gradient              100        0.468       12.066
  constraints           100        0.278        6.878
  jacobian              100        0.013        0.526
  hessian               100        0.048       17.131
  total                            1.555       47.916
                                      3%          97%

Notes on the tables:

  • The table is in seconds, or in ms or us when the smaller of the two totals is small (outputs 3 to 5), so the python column keeps its digits when nearly all the time is in the engine. The fields are always in seconds (output 2).
  • Methods that never ran are left out of the table. NMF has no constraints, but hessian still asks the engine for the (empty) constraint values and Jacobian, so those rows appear with almost no time.
  • For compile, the constraints row is labelled forward.

What the columns mean

  • engine: time inside the engine's own timed routines (Diff_engine_stats).
  • python: everything around them: Python code and the bindings. For setup this includes the engine's node constructors called through the bindings, which the engine does not time.
  • build expressions: time spent in SparseDiffPy's operators and functions creating the expressions the problem uses, before Problem(...) is called.
  • A method is not charged for what it needs from another one: the hessian row does not include the Jacobian or the forward passes.
  • Checking for changed values and pushing parameters to the engine (_refresh) is not timed.

How

  • New binding problem_stats(prob) returns the engine's six timers as a dict. No engine change.
  • Problem measures wall time with perf_counter on each method's cache-miss path and subtracts the engine's number.
  • Build time: the operators and functions users call are wrapped by _timed, which stores the elapsed time on the node they return. Problem adds it up in the walk it already does over its nodes, so shared subexpressions count once and each problem only sees its own expressions. Timed functions call untimed helpers internally (_neg, _pow, _broadcast, _index_flat) so nothing is counted twice; a test checks this for 31 operators and functions.

Behaviour changes

  • The verbose argument of Problem is removed: sp.Problem(..., verbose=True) raises a TypeError. It was undocumented and only made the engine print its own banner when the problem was garbage-collected; nothing is printed unless the user prints prob.stats.
  • Building expressions is about 8% slower because of the timer (about 0.1 to 0.2 us per operator call; 0.096 s to 0.103 s for the 60,000-node loop above).

Tests

tests/test_stats.py (10 tests). Full suite: 131 passed locally (after merging main, which added the PerformanceWarning of #46) against a Release build of this branch. Not run on a free-threaded build.

🤖 Generated with Claude Code

https://claude.ai/code/session_012aJMgsjHjvvLLFNbMGuvAL

dance858 and others added 4 commits December 1, 2026 15:33
prob.stats (and fn.stats for a compiled expression) returns a snapshot
with one row per phase: build, setup, objective, gradient, constraints,
jacobian and hessian. Each row has the seconds spent inside the engine's
own routines, the seconds spent around them (Python and the bindings),
and the number of real evaluations. Printing it gives a table.

The engine's timers are read through a new binding, problem_stats, and
subtracted from wall times measured in Python. A method is not charged
for the stages it needs from another method. The time to build the
expressions is measured in the operators and functions users call and
stored on the node they return; a problem adds it up over its own nodes.
This makes building expressions about 8% slower.

verbose=True now prints the build and setup rows from Python when the
problem is set up. The engine's banner at garbage collection is no longer
triggered from Python.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012aJMgsjHjvvLLFNbMGuvAL
It printed the first two rows of the table that print(prob.stats) gives
in full, compile() never had it, and it was not documented.
Problem(..., verbose=True) now raises a TypeError.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012aJMgsjHjvvLLFNbMGuvAL
With seconds chosen from the grand total, a problem whose time is almost
all in the engine printed 0.000 in every row of the python column.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012aJMgsjHjvvLLFNbMGuvAL
main added the PerformanceWarning for problems written entry by entry
(#46). _collect_leaves now returns both the entry count for the warning
and the build time for stats. The stats test that builds a loop uses 400
entries, below the warning's threshold.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012aJMgsjHjvvLLFNbMGuvAL
@dance858
dance858 merged commit 6de4193 into main Dec 2, 2026
26 of 27 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant