torch.profiler.profile
function profile(fn: (p: Profiler) => Promise<void> | void): Promise<Profiler>function profile(fn: (p: Profiler) => Promise<void> | void, options: ProfilerOptions): Promise<Profiler>High-level context manager for profiling code.
This function provides a convenient way to profile a block of code with automatic setup and cleanup. It returns a Profiler instance with recorded events ready to analyze.
The function can be called with either a function callback or with options and a callback. If the function is async, await the result to ensure GPU operations are synchronized.
Parameters
fn(p: Profiler) => Promise<void> | void- Callback function to profile (if options are provided), or undefined
Returns
Promise<Profiler>– Promise resolving to the Profiler instance with recorded eventsExamples
// Simple usage
const profiler = await profile(async () => {
const x = torch.randn([1000, 1000]);
const y = x.matmul(x);
return y.sum();
});
console.log(profiler.key_averages().table());
// With options
const profiler = await profile(
async () => {
const x = torch.randn([100, 100]);
return x.sum();
},
{ record_shapes: true, profile_memory: true }
);
const events = profiler.get_events();
console.log(events[0].shapes); // Tensor shapes recorded