torch.profiler.record_function
function record_function<T>(name: string, fn: () => T): TRecords a synchronous function execution in the active profiler.
When a profiler is active, this function measures the execution time and memory usage of the provided callback. The measurement is recorded as a CPU activity. If no profiler is active, the function executes with no overhead. Essential for profiling synchronous operations like tensor computations and host code.
For WebGPU, this measures CPU time up to the submission to the GPU queue,
not the actual GPU execution time. Use record_function_async() for more
accurate GPU timing. Useful for:
- Profiling CPU-bound operations
- Measuring Python-like function execution time
- Breaking down long computations into named sections
- Debugging performance bottlenecks
- CPU timing only: For WebGPU, measures CPU submission time, not GPU execution
- No overhead without profiler: When no profiler is active, just calls fn() directly
- Memory tracking: Automatically tracks memory changes during execution
- Return value preserved: Whatever fn() returns is returned unchanged
- Not for async code: Use record_function_async() for Promises
- GPU timing: Does not measure actual GPU execution time for WebGPU ops
Parameters
namestring- Human-readable name of the operation being profiled
fn() => T- Synchronous callback function to execute and measure
Returns
T– The return value of the callback functionExamples
// Basic function profiling
const profiler = new Profiler();
profiler.start();
record_function('matrix_multiply', () => {
const x = torch.randn([100, 100]);
const y = torch.randn([100, 100]);
return x.matmul(y);
});
// Get profiling results
await profiler.stop();
const events = profiler.get_events();
console.log(events[0]); // { name: 'matrix_multiply', duration: 5.32, ... }
// Profile multiple operations
record_function('data_load', () => loadDataBatch());
record_function('preprocessing', () => preprocessImages());
record_function('model_forward', () => model.forward(batch));See Also
- PyTorch torch.profiler.record_function()
- record_function_async - For async operations with GPU synchronization
- Profiler - Main profiler class for starting/stopping profiling