Performance of built-in function Prec

After much narrowing down ( visible bars, moving declarations out of loops, saving array index lookup and storing conditionals ) I realised that what was causing some large lags in my code was simply Prec.

	StrFormat("R/R: %g", (targetPrice - entryPrice) / (entryPrice - stopPrice)), 
                  //Prec((targetPrice - entryPrice) / (entryPrice - stopPrice), 2)), 
	entry, targetPrice, colorGreen, colorBlack, 22

With the code in the comment, my chart with 120k bars was very laggy, I checked and the loop was being accessed about 20 times at most ( using _TRACE ).

I have simply replaced the call to Prec with my own simple significant digits function to resolve the issue.

Curious as to why Prec is so computationally intensive. Has anyone else hit this?

You are calling it on ENTIRE ARRAY (all bars). For StrFormat you don't need entire array, you need SINGLE value. So re-write your code

StrFormat("R/R: %g", Prec(SelectedValue((targetPrice - entryPrice) / (entryPrice - stopPrice));

besides it is absolutely pointless to use Prec with conjunction with StrFormat as StrFormat ITSELF provides rounding to any number of decimals you need. Just use it properly using "%.2f" format instead of "%g":

// proper way to display 2 decimal digits using StrFormat
StrFormat("R/R: %.2g", (targetPrice - entryPrice) / (entryPrice - stopPrice));

If you wanted truncation, not rounding, you can achieve the same by subtracting half step (-0.005) - assuming numbers are positive.

Everything is covered in the manual:

1 Like


@Tomasz Thank you for your attentive response, I shall read harder next time. Making n00b errors...


This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.