Library · Pine Script v5 · Library

LibraryStopwatch

by g-moe· code credited to goodgains

LibraryStopwatch is a Pine Script library designed to measure and benchmark script execution timing.

View on GitHub

GitHub stars3on the repository
Pine versionv5runs as is
Lines of code101
Settings1inputs
LicenceNone statedfile: MPL-2.0
Last update5 months ago27 May 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new library, select all of the template text and paste. Press Save and give it a name.
  4. 4Publish or import itA library draws nothing. Publish it from the editor, then import its functions in your own scripts.

Source Code

101 lines of Pine Script v5 from Tradingview/librarystopwatch.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

librarystopwatch.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © goodgains


//@version=5











// @keywords: stopwatch, library-stopwatch, script-execution-time, execution-timing, ms-per-bar, total-execution-time, elapsed-time, average-time-per-bar, bars-timed, bars-not-timed, bars-analyzed, performance-benchmark, script-benchmark, runtime-measurement, performance-profiling, loop-iterations, execution-stats, timing-stats, script-performance, code-profiling

// @description Provides functions to time the execution of a script.
library("LibraryStopwatch")

loopCount = input.int(100000, "Loop iterations per bar", minval = 0, step = 10000)

// @function Times the execution of a script.
// @returns A tuple of four values: [timePerBarInMs, totalTimeInMs, barsTimed, barsNotTimed]
export stopwatchStats() =>
    // Get time at first bar.
    var int timeBegin = timenow
    // Get ms elapsed since first bar.
    var int timeElapsed = 0
    if not barstate.islast
        timeElapsed := timenow - timeBegin
    // Calculate avg/bar only when time changes.
    var float timePerBarInMs = 0.
    // Total bars timed before last change in "timenow".
    var int barsTimed = 0
    // ————— Bars elapsed since last change in "timenow".
    var int barsNotTimed = 0
    if ta.change(timeElapsed)
        barsTimed := bar_index + 1
        timePerBarInMs  := timeElapsed / barsTimed
    // ————— In between time changes, estimate elapsed time using avg time per bar.
    if not barstate.islast
        // Bars elapsed since last change of time.
        barsNotTimed := bar_index  + 1 - barsTimed
    // ————— Add (bars since "timenow" change * avg bar time) to time elapsed since last "timenow" change to get better estimate of total time elapsed.
    float totalTimeInMs = timeElapsed + (barsNotTimed * timePerBarInMs)
    [timePerBarInMs, totalTimeInMs, barsTimed, barsNotTimed]

// @function    Times the execution of a script.
// @returns     A single value: The time elapsed since the beginning of the script, in ms.
export stopwatch() =>
    // Get time at first bar.
    var int timeBegin = timenow
    // Get ms elapsed since first bar.
    var int timeElapsed = 0
    if not barstate.islast
        timeElapsed := timenow - timeBegin
    // Calculate avg/bar only when time changes.
    var float timePerBarInMs = 0.
    // Total bars timed before last change in "timenow".
    var int barsTimed = 0
    // ————— Bars elapsed since last change in "timenow".
    var int barsNotTimed = 0
    if ta.change(timeElapsed)
        barsTimed := bar_index + 1
        timePerBarInMs  := timeElapsed / barsTimed
    // ————— In between time changes, estimate elapsed time using avg time per bar.
    if not barstate.islast
        // Bars elapsed since last change of time.
        barsNotTimed := bar_index  + 1 - barsTimed
    // ————— Add (bars since "timenow" change * avg bar time) to time elapsed since last "timenow" change to get better estimate of total time elapsed.
    float totalTimeInMs = timeElapsed + (barsNotTimed * timePerBarInMs)

// Examples of calls to both functions.
[timePerBarInMs, totalTimeInMs, barsTimed, barsNotTimed] = stopwatchStats()
msElapsed = stopwatch()

// ————— Script code to time.
var a = 0.
for i = 0 to loopCount
    a := a + i + close + math.pow(hl2, 1 / i) + math.avg(close, open) + math.cos(hlc3)

// —————————— Display results
// ————— Print table at the end of chart.
if barstate.islast
    var table t = table.new(position.middle_right, 1, 1)
    var txt = str.tostring(timePerBarInMs, "ms/bar: #.######\n") +
              str.tostring(totalTimeInMs, "Total time (ms): #,###.######\n") + 
              str.tostring(barsTimed + barsNotTimed, "Bars analyzed: #")
    table.cell(t, 0, 0, txt, bgcolor = color.yellow, text_halign = text.align_right)

// ————— Plot elapsed time.
plot(totalTimeInMs,  "totalTimeInMs", color.gray)
plot(msElapsed,      "msElapsed",     color.new(color.gray, 70), 6)

// ————— Print Data Window values.
plotchar(timePerBarInMs,    "Avg time / bar (ms)",  "", location.top)
plotchar(totalTimeInMs,     "Execution time (ms)",  "", location.top)
plotchar(barsTimed,         "Bars timed",           "", location.top)
plotchar(barsNotTimed,      "Bars not timed",       "", location.top)

Overview

LibraryStopwatch tracks the time elapsed since the script started running using built-in system time variables and estimates execution metrics across processed bars. The library exports functions that calculate the average milliseconds spent per bar, total elapsed runtime, and processed bar counts. It allows developers to profile script efficiency and benchmark code performance using an adjustable loop iteration setting. It functions strictly as a utility module and does not draw on the chart.

Details

Published by

g-moe on GitHub

Code credit

goodgains, as written in the script's header

Type

Library, Pine Script v5

Draws

Library (no plots)

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Loop iterations per barint100000loopCount
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

261 stars

AIActivationFunctionsBipolarSigmoid is a Pine Script library that provides mathematical implementations of the bipolar sigmoid activation function and its derivatives for machine learning algorithms. It calculates bipolar sigmoid values bounded between -1 and

Library v5 AI / machine learning
Updated 4 years ago · None stated GitHub repository of AIActivationFunctionsBipolarSigmoid

KernelFunctions

by artificial-intelligence-edge
75 stars

KernelFunctions is a Pine Script v5 library that exports kernel weight functions for Nadaraya-Watson style estimation. It calculates a Rational Quadratic kernel, a Gaussian kernel based on a radial basis function, and a periodic kernel that models repeating be

Library v5
Updated 2 days ago · MIT GitHub repository of KernelFunctions

Ta

by nersent
29 stars

This Pine Script v5 library exports thin wrappers around built-in technical analysis functions. It covers moving averages, momentum measures such as RSI and CCI, volatility tools including ATR and standard deviation, range extremes, cross detection, and runnin

Library v5
Updated 11 months ago · Custom licence GitHub repository of Ta

Bands

by heyphat
26 stars

This library exports a Band type and functions that build a simple-moving-average basis with upper and lower envelopes from standard deviation. It classifies a source as above, below, or inside those envelopes, measures band width, and scales an imported z-sco

Library v6 Volatility & bandsMoving averages
Updated 2 months ago · AGPL-3.0 GitHub repository of Bands

Mylib

by ferranbt
21 stars

This script serves as a minimal utility library written in Pine Script v6. It provides an exported helper function that calculates the sum of two numeric arguments. As a reusable code library, it produces no visual plots, charts, or trading signals, and it con

Library v6
Updated 7 weeks ago · MPL-2.0 GitHub repository of Mylib

HLevel

by stupenkov
14 stars

HLevel is a Pine Script v5 utility library designed to manage horizontal price levels for cryptocurrency charts. It defines custom types for pivots and levels, along with methods to initialize, add, track, and expire price levels based on pivot high and pivot

Library v5
Updated 3 years ago · None stated GitHub repository of HLevel

More libraries

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers