Optimize the code for Threshold calculation