### Nested Timers Example Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Demonstrates how to use the `@timeit` macro for nested timing. This allows for detailed profiling of hierarchical code structures. ```julia to = TimerOutput() @timeit to "nest 1" begin sleep(0.1) @timeit to "level 2.1" sleep(0.1) for i in 1:20; @timeit to "level 2.2" sleep(0.02); end end @timeit to "nest 2" begin for i in 1:30; @timeit to "level 2.1" sleep(0.01); end @timeit to "level 2.2" sleep(0.1) end ``` -------------------------------- ### Manual Timing with `begin_timed_section!` and `end_timed_section!` Source: https://context7.com/kristofferc/timeroutputs.jl/llms.txt For scenarios not suitable for macro-based timing, manually start and stop timed sections using `begin_timed_section!` and `end_timed_section!`. Ensure `end_timed_section!` is called, typically within a `finally` block, to guarantee section closure even if errors occur. ```julia using TimerOutputs const to = TimerOutput() function manual_timing_example() # Start a timed section section = begin_timed_section!(to, "manual section") try # Do work here sleep(0.1) result = rand(1000) return result finally # Always end the section, even on error end_timed_section!(to, section) end end manual_timing_example() show(to) ``` -------------------------------- ### Accumulating Data for Repeated Calls Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Demonstrates how TimerOutputs.jl accumulates timing data for repeated calls to the same labeled section. The example shows a loop where `sleep` is called multiple times with the label "sleep", and the total time and call count are updated. ```julia # Call to a previously used label accumulates data for i in 1:100 @timeit to "sleep" sleep(0.01) end ``` -------------------------------- ### Manual Timed Section Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Manually start and stop a timed section using `begin_timed_section!` and `end_timed_section!`. Useful for timing specific blocks of code. ```julia section = begin_timed_section!(to, "my section") foo() end_timed_section!(to, section) ``` -------------------------------- ### Resetting a Timer with `reset_timer!` Source: https://context7.com/kristofferc/timeroutputs.jl/llms.txt Use `reset_timer!` to clear all recorded timing data and reset the timer's start time. This is useful for measuring performance over distinct phases or after making code changes. ```julia using TimerOutputs const to = TimerOutput() @timeit to "first_run" sleep(0.1) println("Before reset:") show(to; compact=true, allocations=false) # Reset the timer reset_timer!(to) @timeit to "second_run" sleep(0.05) println("\nAfter reset:") show(to; compact=true, allocations=false) # Reset the default global timer reset_timer!() ``` -------------------------------- ### Get Shared/Named Timers Source: https://context7.com/kristofferc/timeroutputs.jl/llms.txt The `get_timer` function retrieves or creates named timers that can be shared across modules and packages. Requires importing TimerOutputs. ```julia using TimerOutputs # Get or create a named timer (creates if doesn't exist) shared = get_timer("SharedTimer") @timeit shared "module_a_work" sleep(0.05) # In another module/file, access the same timer same_timer = get_timer("SharedTimer") @timeit same_timer "module_b_work" sleep(0.05) # Both sections are in the same timer print_timer(get_timer("SharedTimer")) # Get the default timer default = get_timer("Default") ``` -------------------------------- ### Merge TimerOutput Objects Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Use `merge` to combine two or more TimerOutput objects into a new one. This is useful for aggregating results from different parts of an application or from multi-threaded setups. ```julia julia> to1 = TimerOutput(); to2 = TimerOutput(); julia> @timeit to1 "outer" begin @timeit to1 "inner" begin sleep(1) end end julia> @timeit to2 "outer" begin sleep(1) end julia> show(to1; compact=true, allocations=false) ──────────────────────────────── Section ncalls time %tot ──────────────────────────────── outer 1 1.00s 100% inner 1 1.00s 100% ──────────────────────────────── julia> show(to2; compact=true, allocations=false) ──────────────────────────────── Section ncalls time %tot ──────────────────────────────── outer 1 1.00s 100% ──────────────────────────────── julia> show(merge(to1, to2); compact=true, allocations=false) ──────────────────────────────── Section ncalls time %tot ──────────────────────────────── outer 2 2.00s 100% inner 1 1.00s 50.0% ──────────────────────────────── ``` -------------------------------- ### Resetting a TimerOutput Object Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Resets a `TimerOutput` object by removing all sections and updating the timer's start time. This is done using the `reset_timer!` function. ```julia reset_timer!(to::TimerOutput) ``` -------------------------------- ### Print Timer Output (Customized) Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Shows how to customize timer output using keyword arguments like `allocations` and `compact`. This helps in focusing on specific metrics. ```julia show(to, allocations = false, compact = true) ``` -------------------------------- ### Initialize and Use TimerOutput Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Demonstrates the basic usage of TimerOutputs.jl by initializing a TimerOutput object and timing different code sections using the `@timeit` macro. This includes timing simple functions and accumulating data for repeated calls. ```julia using TimerOutputs # Create a TimerOutput, this is the main type that keeps track of everything. const to = TimerOutput() # Time a section code with the label "sleep" to the `TimerOutput` named "to" @timeit to "sleep" sleep(0.02) # Create a function to later time rands() = rand(10^7) # Time the function, @timeit returns the value being evaluated, just like Base @time rand_vals = @timeit to "randoms" rands(); ``` -------------------------------- ### Instrumenting Existing Functions with TimerOutputs.jl Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Explains how to time an existing function by wrapping it with the `TimerOutput` object. This creates a timed version of the function that can be called like the original, with its execution time recorded. ```julia # Or to instrument an existing function: foo(x) = x + 1 timed_foo = to(foo) timed_foo(5) ``` -------------------------------- ### Indexing and Displaying Nested Timer Data Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Demonstrates how to index into a `TimerOutput` object to access nested sections and display them. Indexing returns a new `TimerOutput` with the selected section as the root, and percentages are relative to this root. ```julia to = TimerOutput() @timeit to "nest 1" begin @timeit to "nest 2" begin @timeit to "nest 3.1" sleep(0.1) @timeit to "nest 3.2" sleep(0.1) @timeit to "nest 3.3" sleep(0.1) end sleep(0.3) end ``` ```julia julia> show(to; compact = true, allocations = false, linechars = :ascii) ------------------------------------- Section ncalls time %tot ------------------------------------- nest 1 1 605ms 100% nest 2 1 304ms 50.2% nest 3.2 1 101ms 16.7% nest 3.1 1 101ms 16.7% nest 3.3 1 101ms 16.7% ------------------------------------- julia> to_2 = to["nest 1"]["nest 2"]; julia> show(to_2; compact = true, allocations = false, linechars = :ascii) --------------------------------- Section ncalls time %tot --------------------------------- nest 3.2 1 101ms 33.3% nest 3.1 1 101ms 33.3% nest 3.3 1 101ms 33.3% --------------------------------- ``` -------------------------------- ### Create TimerOutput Instance Source: https://context7.com/kristofferc/timeroutputs.jl/llms.txt Instantiate a TimerOutput object to track timings. You can create a default timer, a named timer, or access the global default timer. ```julia using TimerOutputs # Create a new named timer const to = TimerOutput() # Create a timer with a custom root label const named_to = TimerOutput("MyApp") # Access the default global timer default = TimerOutputs.get_defaulttimer() ``` -------------------------------- ### Generate Flame Graph from Timer Output Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Visualize timer data using FlameGraphs.jl and ProfileView.jl. Ensure `TimerOutputs`, `FlameGraphs`, and `ProfileView` are imported. ```julia using TimerOutputs, FlameGraphs, ProfileView to = TimerOutput() @timeit to "foo" begin sleep(0.1) @timeit to "bar" begin sleep(0.1) @timeit to "baz" begin sleep(0.1) end end end ProfileView.view(flamegraph(to)) ``` ```julia ProfileView.view(flamegraph(to, crop_root=true)) ``` -------------------------------- ### Generate and View Flame Graph with TimerOutputs Source: https://context7.com/kristofferc/timeroutputs.jl/llms.txt This snippet shows how to use TimerOutputs.jl to time code sections and then generate a flame graph using FlameGraphs.jl. Ensure FlameGraphs and ProfileView packages are loaded. The `crop_root=true` option can be used to exclude the root timer span from the visualization. ```julia using TimerOutputs, FlameGraphs, ProfileView const to = TimerOutput() @timeit to "computation" begin @timeit to "load_data" sleep(0.1) @timeit to "process" begin @timeit to "step1" sleep(0.15) @timeit to "step2" sleep(0.1) end @timeit to "save_results" sleep(0.05) end # Generate flame graph fg = flamegraph(to) ProfileView.view(fg) # Crop to children only (exclude root timer span) ProfileView.view(flamegraph(to, crop_root=true)) ``` -------------------------------- ### Index and Query Timer Data Source: https://context7.com/kristofferc/timeroutputs.jl/llms.txt Access nested timers using bracket indexing and query timing data with ncalls, time, allocated, tottime, and totallocated functions. Requires importing TimerOutputs. ```julia using TimerOutputs const to = TimerOutput() @timeit to "level1" begin @timeit to "level2" begin @timeit to "level3" sleep(0.1) end sleep(0.05) end # Index into nested timers level2_timer = to["level1"]["level2"] show(level2_timer; compact=true, allocations=false) # Query timing data (time in nanoseconds, allocations in bytes) println("Level 1 calls: ", TimerOutputs.ncalls(to["level1"])) println("Level 2 time (ns): ", TimerOutputs.time(to["level1"]["level2"])) println("Level 2 allocated (bytes): ", TimerOutputs.allocated(to["level1"]["level2"])) # Get total measured time/allocations for root timer println("Total time (ns): ", TimerOutputs.tottime(to)) println("Total allocated (bytes): ", TimerOutputs.totallocated(to)) # Check if section exists println("Has 'level1': ", haskey(to, "level1")) println("Has 'nonexistent': ", haskey(to, "nonexistent")) ``` -------------------------------- ### Customizing Timer Output with `print_timer` and `show` Source: https://context7.com/kristofferc/timeroutputs.jl/llms.txt Customize the display of timing data using keyword arguments with `print_timer` and `show`. Options include adding a title, hiding specific columns like allocations or average time, changing the sort order, and using ASCII characters for table borders. ```julia using TimerOutputs const to = TimerOutput() # Create some timing data @timeit to "section_a" sleep(0.1) @timeit to "section_b" for i in 1:5; sleep(0.02); end @timeit to "section_c" rand(10^6) # Default output print_timer(to) # With title print_timer(to; title="Performance Report") # Hide allocations column print_timer(to; allocations=false) # Compact mode (hide avg column) print_timer(to; compact=true) # Sort by different criteria: :time (default), :ncalls, :allocations, :name, :firstexec print_timer(to; sortby=:ncalls) print_timer(to; sortby=:name) # Use ASCII characters instead of Unicode for table borders print_timer(to; linechars=:ascii) # Combine options show(to; allocations=false, compact=true, sortby=:time, linechars=:ascii) # Output: # ------------------------------------ # Section ncalls time %tot # ------------------------------------ # section_b 5 102ms 49.3% # section_a 1 101ms 48.8% # section_c 1 3.91ms 1.89% # ------------------------------------ ``` -------------------------------- ### Nested Timing with TimerOutputs.jl Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Illustrates how to use nested `@timeit` macros to time sections within other timed sections. It shows how different labels at the same level are handled and how repeated calls to the same label within a nested scope accumulate data. ```julia # Nested sections (sections with same name are not accumulated # if they have different parents) function time_test() @timeit to "nest 1" begin sleep(0.1) # 3 calls to the same label @timeit to "level 2.1" sleep(0.03) @timeit to "level 2.1" sleep(0.03) @timeit to "level 2.1" sleep(0.03) @timeit to "level 2.2" sleep(0.2) end @timeit to "nest 2" begin @timeit to "level 2.1" sleep(0.3) @timeit to "level 2.2" sleep(0.4) end end time_test() ``` -------------------------------- ### Basic Timing with @timeit Source: https://context7.com/kristofferc/timeroutputs.jl/llms.txt Use the @timeit macro to time expressions, function calls, or code blocks. It returns the value of the timed expression and accumulates results under the given label. The `show` function displays the timing results. ```julia using TimerOutputs const to = TimerOutput() # Time a simple expression @timeit to "sleep" sleep(0.02) # Time a function call and capture return value function expensive_computation() return rand(10^6) end result = @timeit to "computation" expensive_computation() # Time a block of code @timeit to "processing" begin data = rand(1000, 1000) processed = data * data' end # Print the timing results show(to) ``` -------------------------------- ### Exception-Safe Timing with TimerOutputs.jl Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Demonstrates how `@timeit` handles code that throws an exception. The timing data is still recorded correctly even if an error occurs within the timed block, ensuring that performance metrics are captured reliably. ```julia # exception safe function i_will_throw() @timeit to "throwing" begin sleep(0.5) throw(error("this is fine...")) print("nope") end end i_will_throw() ``` -------------------------------- ### Querying Total Time and Allocations Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Functions to retrieve the total time spent in the root timer (`tottime`) and the total memory allocated (`totallocated`). ```julia julia> TimerOutputs.tottime(to) 604937208 julia> TimerOutputs.totallocated(to) 7632 ``` -------------------------------- ### Annotating Function Definitions with @timeit Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Shows how to use the `@timeit` macro directly on function definitions. This automatically instruments the function so that all its calls will be timed under the specified label. ```julia # Can also annotate function definitions @timeit to funcdef(x) = x funcdef(2) ``` -------------------------------- ### Print Timer Output Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Displays a formatted table of timing and allocation data. This is the default way to view timer results. ```julia show(to) ``` -------------------------------- ### Use the Default Global Timer Source: https://context7.com/kristofferc/timeroutputs.jl/llms.txt Functions operate on a built-in global timer when no `TimerOutput` instance is specified. Requires importing TimerOutputs. ```julia using TimerOutputs # Reset the default timer reset_timer!() # Time using default timer (no TimerOutput argument) @timeit "global_section_1" sleep(0.05) @timeit "global_section_2" begin @timeit "nested" sleep(0.03) end # Print the default timer print_timer() # Access the default timer instance default_to = TimerOutputs.get_defaulttimer() println("Total time: ", TimerOutputs.tottime(default_to), " ns") ``` -------------------------------- ### Debug Timing with @timeit_debug Source: https://context7.com/kristofferc/timeroutputs.jl/llms.txt The `@timeit_debug` macro provides zero-overhead timing that can be enabled/disabled per module, ideal for instrumenting library code. Requires importing TimerOutputs. ```julia using TimerOutputs const to = TimerOutput() # Use @timeit_debug for conditional timing @timeit_debug to "debug_section" begin sleep(0.1) end # By default, debug timings are disabled (zero overhead) show(to) # Shows nothing # Enable debug timings for the current module TimerOutputs.enable_debug_timings(@__MODULE__) # Now debug timings will be recorded @timeit_debug to "now_recorded" sleep(0.05) show(to) # Disable again TimerOutputs.disable_debug_timings(@__MODULE__)) ``` -------------------------------- ### Querying Timer Data: ncalls, time, allocated Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Provides functions to query accumulated data for a section: `ncalls` for the number of calls, `time` for the total time in nanoseconds, and `allocated` for memory allocations in bytes. ```julia julia> TimerOutputs.ncalls(to["nest 1"]) 1 julia> TimerOutputs.time(to["nest 1"]["nest 2"]) 350441733 julia> TimerOutputs.allocated(to["nest 1"]["nest 2"]) 5280 ``` -------------------------------- ### Use Shared Timers in Julia Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Demonstrates using a shared, named timer across different modules. `get_timer` retrieves or creates a named timer. Be cautious with top-level calls during precompilation and extensive library use to avoid namespace collisions. ```julia module UseTimer using TimerOutputs: @timeit, get_timer function foo() to = get_timer("Shared") @timeit get_timer("Shared") "foo" sleep(0.1) end end @timeit get_timer("Shared") "section1" begin UseTimer.foo() sleep(0.01) end ``` -------------------------------- ### Nested Timing Sections with @timeit Source: https://context7.com/kristofferc/timeroutputs.jl/llms.txt The @timeit macro supports hierarchical nesting. Sections with the same label under different parents are tracked separately, allowing detailed breakdown of sub-operations. The output can be customized using arguments like `allocations=false` and `compact=true`. ```julia using TimerOutputs const to = TimerOutput() function time_nested_operations() @timeit to "outer 1" begin sleep(0.1) @timeit to "inner" sleep(0.05) @timeit to "inner" sleep(0.05) # Accumulates with previous "inner" end @timeit to "outer 2" begin @timeit to "inner" sleep(0.1) # Different parent, tracked separately end end time_nested_operations() show(to; allocations=false, compact=true) ``` -------------------------------- ### Complement Timed Sections in Julia Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Creates a timer, times two sections with a nested section, complements the timer to include untimed portions, and prints the detailed results. Use `complement!` to account for time spent outside explicitly timed blocks. ```julia to = TimerOutput() @timeit to "section1" sleep(0.02) @timeit to "section2" begin @timeit to "section2.1" sleep(0.1) sleep(0.01) end TimerOutputs.complement!(to) ``` -------------------------------- ### Serialize Timer Output to Dictionary Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Convert timer data to a nested dictionary structure for serialization, such as to JSON. Requires the `TimerOutputs` module. ```julia julia> to = TimerOutput(); julia> @timeit to "nest 1" begin sleep(0.1) @timeit to "level 2.1" sleep(0.1) for i in 1:20; @timeit to "level 2.2" sleep(0.02); end end julia> TimerOutputs.todict(to) Dict{String, Any} with 6 entries: "total_time_ns" => 726721166 "total_allocated_bytes" => 474662 "time_ns" => 0 "n_calls" => 0 "allocated_bytes" => 0 "inner_timers" => Dict{String, Any}("nest 1"=>Dict{String, Any}("total_time_ns"=>611383374, "total_allocated_bytes"=>11888, "time_ns"=>726721166, "n_calls"=>1, "allocated_bytes"=>474662, "inner_timers"=>Dict{String, Any}("level 2.1"=>Dict{String, Any}("total_time_ns"=>0, "total_allocated_bytes"=>0, "time_ns"=>115773750, "n_calls"=>1, "allocated_bytes"=>8064, "inner_timers"=>Dict{String, Any}()), "level 2.2"=>Dict{String, Any}("total_time_ns"=>0, "total_allocated_bytes"=>0, "time_ns"=>495609624, "n_calls"=>20, "allocated_bytes"=>3824, "inner_timers"=>Dict{String, Any}())))) ``` ```julia julia> using JSON3 # or JSON julia> JSON3.write(TimerOutputs.todict(to)) "{\"total_time_ns\":712143250,\"total_allocated_bytes\":5680,\"time_ns\":0,\"n_calls\":0,\"allocated_bytes\":0,\"inner_timers\":{\"nest 1\":{\"total_time_ns\":605922416,\"total_allocated_bytes\":4000,\"time_ns\":712143250,\"n_calls\":1,\"allocated_bytes\":5680,\"inner_timers\":{\"level 2.1\":{\"total_time_ns\":0,\"total_allocated_bytes\":0,\"time_ns\":106111333,\"n_calls\":1,\"allocated_bytes\":176,\"inner_timers\":{}},\"level 2.2\":{\"total_time_ns\":0,\"total_allocated_bytes\":0,\"time_ns\":499811083,\"n_calls\":20,\"allocated_bytes\":3824,\"inner_timers\":{}}}}}}" ``` -------------------------------- ### Enabling and Disabling Timers Dynamically Source: https://context7.com/kristofferc/timeroutputs.jl/llms.txt Control timing activity using `enable_timer!` and `disable_timer!`. The `@notimeit` macro provides a way to temporarily exclude specific code blocks from timing, even when timers are enabled. ```julia using TimerOutputs const to = TimerOutput() @timeit to "recorded" sleep(0.05) # Disable the timer disable_timer!(to) @timeit to "not_recorded" sleep(0.1) # This won't be recorded # Re-enable the timer enable_timer!(to) @timeit to "also_recorded" sleep(0.05) # Use @notimeit to temporarily disable timing @notimeit to begin @timeit to "skipped" sleep(0.1) # This won't be recorded end show(to; compact=true, allocations=false) # Output only shows "recorded" and "also_recorded" ``` -------------------------------- ### Thread-Safe Merging with `merge!` and `tree_point` Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Demonstrates using `merge!` with `tree_point` for thread-safe merging of TimerOutput objects, suitable for multi-threaded applications. `merge!` uses a lock to ensure thread safety. ```julia julia> using TimerOutputs julia> to = TimerOutput() julia> @timeit to "1" begin @timeit to "1.1" sleep(0.1) @timeit to "1.2" sleep(0.1) @timeit to "1.3" sleep(0.1) end julia> @timeit to "2" Threads.@spawn begin to2 = TimerOutput() @timeit to2 "2.1" sleep(0.1) @timeit to2 "2.2" sleep(0.1) @timeit to2 "2.3" sleep(0.1) merge!(to, to2, tree_point = ["2"]) end julia> to ────────────────────────────────────────────────────────────────── Time Allocations ────────────────────── ─────────────────────── Tot / % measured: 3.23s / 9.79% 13.5MiB / 36.9% Section ncalls time %tot avg alloc %tot avg ────────────────────────────────────────────────────────────────── 1 1 309ms 98.0% 309ms 4.55MiB 91.5% 4.55MiB 1.3 1 106ms 33.6% 106ms 320B 0.01% 320B 1.2 1 102ms 32.3% 102ms 320B 0.01% 320B 1.1 1 101ms 32.0% 101ms 4.54MiB 91.4% 4.54MiB 2 1 6.47ms 2.05% 6.47ms 435KiB 8.54% 435KiB 2.2 1 106ms 33.6% 106ms 480B 0.01% 480B 2.3 1 105ms 33.4% 105ms 144B 0.00% 144B 2.1 1 103ms 32.5% 103ms 5.03MiB 101% 5.03MiB ────────────────────────────────────────────────────────────────── ``` -------------------------------- ### Serialize Timer Data to Dictionary Source: https://context7.com/kristofferc/timeroutputs.jl/llms.txt The `todict` function converts a `TimerOutput` to a nested dictionary structure for JSON serialization or programmatic access. Requires importing TimerOutputs and optionally JSON3 or JSON. ```julia using TimerOutputs const to = TimerOutput() @timeit to "outer" begin @timeit to "inner_a" sleep(0.05) @timeit to "inner_b" sleep(0.03) end # Convert to dictionary data = TimerOutputs.todict(to) # Access timing data programmatically println("Keys: ", keys(data)) # Keys: n_calls, time_ns, allocated_bytes, total_allocated_bytes, total_time_ns, inner_timers println("Inner timers: ", keys(data["inner_timers"])) println("Outer time (ns): ", data["inner_timers"]["outer"]["time_ns"]) println("Inner A calls: ", data["inner_timers"]["outer"]["inner_timers"]["inner_a"]["n_calls"]) # Serialize to JSON using JSON3 # or JSON json_str = JSON3.write(TimerOutputs.todict(to)) println(json_str) ``` -------------------------------- ### Instrumenting Functions with `to` Source: https://context7.com/kristofferc/timeroutputs.jl/llms.txt Use the `to` function to automatically instrument a function, creating a timed version. You can provide a custom label for clearer output. The instrumented function can then be called like the original. ```julia using TimerOutputs # Define a regular function function process_data(data) return sum(data .^ 2) end # Instrument the function timed_process = to(process_data) # Or with a custom label timed_process_labeled = to(process_data, "data_processing") # Use the instrumented function result1 = timed_process(rand(10000)) result2 = timed_process(rand(10000)) result3 = timed_process_labeled(rand(10000)) show(to; compact=true) # Output shows timing for both "process_data" and "data_processing" labels ``` -------------------------------- ### Timing Function Definitions with @timeit Source: https://context7.com/kristofferc/timeroutputs.jl/llms.txt Annotate function definitions directly with @timeit to automatically time every call to that function. This can be done for standard function definitions, short-form definitions, or with custom labels. ```julia using TimerOutputs const to = TimerOutput() # Annotate a function definition @timeit to function compute_fft(data) # Simulated FFT computation sleep(0.01) return fft_result = sum(data) end # Short-form function definition @timeit to square(x) = x^2 # With custom label @timeit to "matrix_multiply" function matmul(A, B) return A * B end # Call the timed functions compute_fft(rand(100)) compute_fft(rand(100)) square(5) matmul(rand(10, 10), rand(10, 10)) show(to; compact=true, allocations=false) ``` -------------------------------- ### Merging Multiple Timers with `merge` and `merge!` Source: https://context7.com/kristofferc/timeroutputs.jl/llms.txt Combine timing data from multiple `TimerOutput` instances using `merge` (creates a new timer) or `merge!` (modifies an existing timer). This is particularly useful for aggregating results from parallel computations. ```julia using TimerOutputs # Create separate timers (e.g., for different threads) to1 = TimerOutput() to2 = TimerOutput() @timeit to1 "task" begin @timeit to1 "subtask" sleep(0.1) end @timeit to2 "task" begin @timeit to2 "subtask" sleep(0.1) end # Merge into a new timer merged = merge(to1, to2) show(merged; compact=true, allocations=false) # Output: # ──────────────────────────────── # Section ncalls time %tot # ──────────────────────────────── # task 2 202ms 100% # subtask 2 201ms 99.5% # ──────────────────────────────── ``` -------------------------------- ### Disabling and Re-enabling Timers Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Shows how to selectively disable and re-enable a `TimerOutput` object using `disable_timer!` and `enable_timer!`. Code timed while the timer is disabled will not be recorded. ```julia # Use disable_timer! to selectively turn off a timer, enable_timer! turns it on again disable_timer!(to) @timeit to "not recorded" sleep(0.1) enable_timer!(to) ``` -------------------------------- ### Print Timer Results in Julia Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Prints the results of a given TimerOutput instance. This function displays a detailed breakdown of time and allocations for each section. ```julia print_timer(to) ``` -------------------------------- ### Compute Complement Time for Unmeasured Code Source: https://context7.com/kristofferc/timeroutputs.jl/llms.txt The `complement!` function adds entries for time spent outside of timed subsections. This helps identify unmeasured code paths. Requires importing TimerOutputs. ```julia using TimerOutputs const to = TimerOutput() @timeit to "outer" begin @timeit to "timed_inner" sleep(0.05) sleep(0.1) # This time is not directly measured end println("Before complement:") show(to; compact=true, allocations=false) TimerOutputs.complement!(to) println("\nAfter complement:") show(to; compact=true, allocations=false) # Output now shows "~outer~" section capturing the unmeasured 0.1s ``` -------------------------------- ### Flatten Timer Output Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Uses `TimerOutputs.flatten` to accumulate data for sections with identical labels, simplifying the output for deeply nested timers. ```julia to_flatten = TimerOutputs.flatten(to) ``` ```julia show(to_flatten; compact = true, allocations = false) ``` -------------------------------- ### Use Default Timer in Julia Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Resets the global timer, times two sections, and prints the results. This is useful for quick profiling without explicit timer management. ```julia reset_timer!() @timeit "section" sleep(0.02) @timeit "section2" sleep(0.1) print_timer() ``` -------------------------------- ### Temporarily Disabling Timers with @notimeit Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Introduces the `@notimeit` macro, which temporarily disables timing for a block of code and automatically re-enables it afterward if it was previously enabled. This is useful for excluding specific sections from timing without manual management. ```julia # Use @notimeit to disable timer and re-enable it afterwards (if it was enabled # before) @notimeit to time_test() ``` -------------------------------- ### Merge Timers with Tree Point Source: https://context7.com/kristofferc/timeroutputs.jl/llms.txt Merges a sub-timer into a main timer at a specific tree point. Ensure the main timer is initialized before merging. ```julia using TimerOutputs main_to = TimerOutput() @timeit main_to "main" sleep(0.01) sub_to = TimerOutput() @timeit sub_to "sub_work" sleep(0.05) merge!(main_to, sub_to, tree_point=["main"]) ``` -------------------------------- ### Flattening Nested Timers with `flatten` Source: https://context7.com/kristofferc/timeroutputs.jl/llms.txt The `flatten` function consolidates timing data by accumulating statistics for sections with identical labels, regardless of their nesting depth. This is useful for simplifying complex nested timing structures. ```julia using TimerOutputs const to = TimerOutput() @timeit to "parent_a" begin sleep(0.1) @timeit to "child" sleep(0.05) end @timeit to "parent_b" begin @timeit to "child" sleep(0.1) # Same label, different parent end println("Original (nested):") show(to; allocations=false, compact=true) # Flatten the timer to_flat = TimerOutputs.flatten(to) println("\nFlattened:") show(to_flat; allocations=false, compact=true) # Output shows "child" with combined stats (2 calls, ~150ms total) ``` -------------------------------- ### Print Shared Timer Results in Julia Source: https://github.com/kristofferc/timeroutputs.jl/blob/master/README.md Prints the results of the shared timer named 'Shared'. This provides a consolidated view of timing information across different parts of the application that use this shared timer. ```julia print_timer(get_timer("Shared")) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.