Your question is Optimize Code for Speed. Take a moment with it on the right.
Talk me through your thinking if you like. When you're confident, submit your answer and I'll grade it like a real screen (7/10 or better passes).
An equipment-test QA harness ingests sensor readings from stress-test rigs and flags anomalies against a calibration reference. The method below has started taking minutes to process a single rig's readings as test volume has grown. Optimize this piece of code to reduce execution time.
public List<string> FindAnomalies(List<SensorReading> readings, string calibrationPath)
{
ArrayList seenIds = new ArrayList();
var report = "";
foreach (var reading in readings)
{
var calibrationLines = File.ReadAllLines(calibrationPath);
double baseline = 0;
foreach (var line in calibrationLines)
{
if (line.StartsWith(reading.SensorId))
{
baseline = double.Parse(line.Split(',')[1]);
break;
}
}
if (seenIds.Contains(reading.ReadingId))
{
continue;
}
seenIds.Add(reading.ReadingId);
var outOfRange = readings.Where(r => r.SensorId == reading.SensorId && Math.Abs(r.Value - baseline) > 5.0).ToList();
if (outOfRange.Count > 0)
{
report += reading.SensorId + ": " + reading.Value + " vs baseline " + baseline + "
";
}
}
return report.Split('
').ToList();
}
readings regularly has tens of thousands of entries per stress-test rig. Explain what makes this slow and how you would fix it.