Here's a Python script that analyzes logcat logs to calculate time differences between "KPI start" and "KPI end" events, and provides min/max/average statistics:
python
import re
from datetime import datetime
import statistics
def parse_timestamp(log_line):
"""Parse timestamp from logcat line"""
# Assuming logcat format: MM-DD HH:MM:SS.mmm
timestamp_pattern = r'(\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3})'
match = re.search(timestamp_pattern, log_line)
if match:
return datetime.strptime(match.group(1), '%m-%d %H:%M:%S.%f')
return None
def calculate_kpi_durations(log_file_path):
"""Calculate durations between KPI start and end events"""
kpi_durations = []
start_time = None
try:
with open(log_file_path, 'r') as file:
for line in file:
# Look for KPI start
if "KPI start" in line:
start_time = parse_timestamp(line)
# Look for KPI end and calculate duration
elif "KPI end" in line and start_time:
end_time = parse_timestamp(line)
if end_time:
duration = (end_time - start_time).total_seconds() * 1000 # Convert to milliseconds
kpi_durations.append(duration)
start_time = None # Reset start time for next KPI pair
return kpi_durations
except FileNotFoundError:
print(f"Error: Log file '{log_file_path}' not found")
return []
except Exception as e:
print(f"Error processing log file: {str(e)}")
return []
def print_statistics(durations):
"""Print statistics of KPI durations"""
if not durations:
print("No KPI durations found in the log file")
return
print("\nKPI Duration Statistics (in milliseconds):")
print(f"Total measurements: {len(durations)}")
print(f"Minimum duration: {min(durations):.2f} ms")
print(f"Maximum duration: {max(durations):.2f} ms")
print(f"Average duration: {statistics.mean(durations):.2f} ms")
if len(durations) > 1:
print(f"Standard deviation: {statistics.stdev(durations):.2f} ms")
def main():
# Specify your log file path
log_file_path = "path/to/your/logcat.log"
# Calculate durations
durations = calculate_kpi_durations(log_file_path)
# Print statistics
print_statistics(durations)
# Optionally, print all individual durations
if durations:
print("\nIndividual KPI durations (in milliseconds):")
for i, duration in enumerate(durations, 1):
print(f"Measurement {i}: {duration:.2f} ms")
if __name__ == "__main__":
main()
This script does the following:
The parse_timestamp function extracts and parses timestamps from logcat lines using a regular expression pattern. It assumes a standard logcat timestamp format (MM-DD HH:MM:SS.mmm).
The calculate_kpi_durations function:
Reads the log file line by line
Looks for "KPI start" and "KPI end" markers
Calculates the time difference between matching pairs
Returns a list of durations in milliseconds
The print_statistics function:
Calculates and displays min/max/average durations
Shows the total number of measurements
Calculates standard deviation (if there are multiple measurements)
Handles the case where no KPI pairs are found
The main function orchestrates the execution and provides a place to specify your log file path.
To use this script:
Save it as kpi_analyzer.py
Modify the log_file_path variable in the main function to point to your logcat file
Support for different timestamp formats by modifying the parse_timestamp function
Filtering by specific KPI types if your logs contain different types of KPIs
Export results to a file:
python
def save_results(durations, output_file):
with open(output_file, 'w') as f:
f.write("KPI Duration Statistics (in milliseconds):\n")
f.write(f"Total measurements: {len(durations)}\n")
# Add more statistics as needed
Error handling is included for:
File not found
Invalid timestamp formats
Missing KPI pairs
General exceptions
Remember to adjust the timestamp pattern in parse_timestamp if your logcat uses a different format.