MYCSS

2024-11-13

Performance Comparison of Python Function Implementations for Equivalent Output

😄 Цікаво інколи оптимізувати код.
Отримав такі рішення для випадку коли не завжди є рядок з всіма параметрами і його треба розбити на частини.

📅 Рядок category може бути "W", "P-V-00", "S", "P-V-01", "L-X", "L-X-A-B-C-D"
Проведено 10_000_000 замірів 8 разів і отримано середні значення часу виконання.

Perfomance Comparison

🔖Наведено топ 3 результати вимірювань. 

  1. Як не дивно, на першому місці Version 5, коли є всі елементи в категорії, але на останньому коли не всі елементи є - вітання до try-except.
    Можна провести алегорію з приказками "Як тривога, то до Бога", "Без біди Бога не кличуть".
  2. На другому місці Version 6 та Version 9 в інших випадках.

versions code

import timeit
import matplotlib.pyplot as plt
def version_1(category: str) -> tuple[str, str | None, str | None]:
category_list = category.split("-", 4)
category_list_length = len(category_list)
folder_type = category_list[0]
version_tag = category_list[1] if category_list_length > 1 else None
version = category_list[2] if category_list_length > 2 else None
return folder_type, version_tag, version
def version_2(category: str) -> tuple[str, str | None, str | None]:
return tuple((category.split("-", 4) + [None, None])[:3])
def version_3(category: str) -> tuple[str, str | None, str | None]:
category_list = category.split("-", 4)[:3]
category_list_length = len(category_list)
folder_type = category_list[0]
version_tag, version = None, None
match category_list_length:
case 2:
version_tag = category_list[1]
case 3:
version_tag = category_list[1]
version = category_list[2]
return folder_type, version_tag, version
def version_4(category: str) -> tuple[str, str | None, str | None]:
category_list = category.split("-", 4)
category_list_length = len(category_list)
folder_type = category_list[0]
version_tag, version = None, None
if category_list_length > 1:
version_tag = category_list[1]
if category_list_length > 2:
version = category_list[2]
return folder_type, version_tag, version
def version_5(category: str) -> tuple[str, str | None, str | None]:
category_list = category.split("-", 4)
folder_type = category_list[0]
try:
version_tag = category_list[1]
except IndexError:
version_tag = None
try:
version = category_list[2]
except IndexError:
version = None
return folder_type, version_tag, version
def version_6(category: str) -> tuple[str, str | None, str | None]:
category_list = category.split("-", 4)
category_list_length = len(category_list)
return (
category_list[0],
category_list[1] if category_list_length > 1 else None,
category_list[2] if category_list_length > 2 else None,
)
def version_7(category: str) -> tuple[str, str | None, str | None]:
category_list = category.split("-", 4)
category_list_length = len(category_list)
folder_type = category_list[0]
version_tag, version = None, None
if category_list_length > 2:
version_tag = category_list[1]
version = category_list[2]
elif category_list_length > 1:
version_tag = category_list[1]
return folder_type, version_tag, version
def version_8(category: str) -> tuple[str, str | None, str | None]:
category_list = category.split("-", 4)
category_list_length = len(category_list)
folder_type = category_list[0]
version_tag, version = None, None
if category_list_length > 2:
version_tag, version = category_list[1:3]
elif category_list_length > 1:
version_tag = category_list[1]
return folder_type, version_tag, version
def version_9(category: str) -> tuple[str, str | None, str | None]:
category_list = category.split("-", 4)
category_list_length = len(category_list)
folder_type = category_list[0]
version_tag, version = None, None
if category_list_length > 2:
version_tag = category_list[1]
version = category_list[2]
elif category_list_length > 1:
version_tag = category_list[1]
return folder_type, version_tag, version
def plot_mesures(plot_results: dict, output_file="performance_comparison.png"):
plt.figure(figsize=(12, 8))
for fun_name in plot_results:
plt.plot(categories, plot_results[fun_name], marker="o", label=fun_name.title())
plt.title("Performance Comparison of Different Versions")
plt.xlabel("Category")
plt.ylabel("Average Time (seconds)")
plt.grid(True)
plt.legend()
plt.tight_layout()
plt.savefig(output_file, dpi=300) # Save as PNG with high resolution
print(f"Saved results to: {output_file}")
# plt.savefig("performance_comparison.pdf") # Save as PDF
functions_list = [
(lambda: version_1(cat), "version_1"),
(lambda: version_2(cat), "version_2"),
(lambda: version_3(cat), "version_3"),
(lambda: version_4(cat), "version_4"),
(lambda: version_5(cat), "version_5"),
(lambda: version_6(cat), "version_6"),
(lambda: version_7(cat), "version_7"),
(lambda: version_8(cat), "version_8"),
(lambda: version_9(cat), "version_9"),
]
categories = ["", "W", "S", "L-X", "P-V-00", "P-V-01", "L-X-A-B-C-D"]
times = 10_000_000
repeat = 8
print(f"{times=}, {repeat=}")
results = {fun_name: [] for _, fun_name in functions_list}
for cat in categories:
print(f"\nCategory: '{cat}'")
for fun, fun_name in functions_list:
result_version = fun()
time_version = timeit.repeat(fun, number=times, repeat=repeat)
avg_time_version = sum(time_version) / len(time_version)
results[fun_name].append(avg_time_version)
print(
f" - {fun_name.title()}. Time: {[f'{t:.4f}' for t in time_version]} "
f"avg: {avg_time_version:.4f} seconds. Result: {result_version}"
)
plot_mesures(results)
print("Press Enter to exit...")
input()
"""
times=10000000, repeat=8
Category: ''
- Version_1. Time: ['6.5469', '5.3129', '4.7609', '5.2324', '4.9136', '4.3683', '4.0807', '3.8416'] avg: 4.8822 seconds. Result: ('', None, None)
- Version_2. Time: ['5.3210', '5.5728', '5.4094', '4.9747', '4.9423', '4.9268', '4.8890', '5.0534'] avg: 5.1362 seconds. Result: ('', None, None)
- Version_3. Time: ['4.6867', '5.0038', '4.8769', '4.7945', '5.2371', '4.9345', '5.5462', '5.2584'] avg: 5.0423 seconds. Result: ('', None, None)
- Version_4. Time: ['3.7000', '3.6609', '3.6348', '3.6565', '3.9045', '3.5578', '3.5027', '4.0963'] avg: 3.7142 seconds. Result: ('', None, None)
- Version_5. Time: ['8.5873', '8.5875', '8.5799', '8.6520', '8.7276', '9.0289', '8.8838', '8.6852'] avg: 8.7165 seconds. Result: ('', None, None)
- Version_6. Time: ['3.4239', '3.2351', '3.4304', '3.3638', '3.3331', '3.3497', '3.3355', '3.5539'] avg: 3.3782 seconds. Result: ('', None, None)
- Version_7. Time: ['3.8983', '3.9969', '4.7141', '3.9817', '3.6071', '3.6497', '3.5203', '3.7359'] avg: 3.8880 seconds. Result: ('', None, None)
- Version_8. Time: ['4.0271', '3.5191', '3.7749', '3.7132', '3.6082', '3.7608', '3.7120', '3.7856'] avg: 3.7376 seconds. Result: ('', None, None)
- Version_9. Time: ['4.0229', '3.6130', '3.9693', '4.1655', '4.8472', '4.0385', '3.6856', '3.7360'] avg: 4.0098 seconds. Result: ('', None, None)
Category: 'W'
- Version_1. Time: ['3.9735', '4.4084', '4.6966', '3.9630', '4.4731', '4.3496', '3.9428', '4.0479'] avg: 4.2319 seconds. Result: ('W', None, None)
- Version_2. Time: ['5.7056', '5.7760', '5.2814', '5.7141', '5.6529', '5.4931', '6.1959', '5.2802'] avg: 5.6374 seconds. Result: ('W', None, None)
- Version_3. Time: ['4.9920', '5.9082', '5.3019', '5.3031', '5.4892', '5.7232', '6.4695', '5.5668'] avg: 5.5942 seconds. Result: ('W', None, None)
- Version_4. Time: ['4.7738', '4.4285', '4.3708', '4.6141', '4.6172', '4.9233', '4.0507', '4.0172'] avg: 4.4744 seconds. Result: ('W', None, None)
- Version_5. Time: ['10.2896', '10.4188', '9.6170', '11.1500', '10.3099', '10.1927', '13.6753', '10.3435'] avg: 10.7496 seconds. Result: ('W', None, None)
- Version_6. Time: ['3.9409', '3.7860', '3.6576', '3.6537', '3.5699', '3.7873', '4.0961', '4.7312'] avg: 3.9028 seconds. Result: ('W', None, None)
- Version_7. Time: ['4.5517', '4.1212', '4.0513', '4.0928', '4.5847', '4.6190', '4.5643', '4.5007'] avg: 4.3857 seconds. Result: ('W', None, None)
- Version_8. Time: ['4.5258', '3.7791', '3.9630', '4.0611', '3.8162', '3.7991', '4.0390', '4.9050'] avg: 4.1110 seconds. Result: ('W', None, None)
- Version_9. Time: ['4.2807', '4.1148', '4.3841', '4.7482', '4.9717', '4.2944', '4.0291', '4.4828'] avg: 4.4132 seconds. Result: ('W', None, None)
Category: 'S'
- Version_1. Time: ['4.0563', '4.2409', '3.7139', '4.1233', '3.9169', '3.8436', '4.1157', '3.8825'] avg: 3.9866 seconds. Result: ('S', None, None)
- Version_2. Time: ['5.6536', '6.1434', '5.4589', '5.3495', '5.2841', '5.3103', '5.8305', '5.7248'] avg: 5.5944 seconds. Result: ('S', None, None)
- Version_3. Time: ['6.9128', '5.7496', '5.6832', '5.1064', '5.3622', '6.0059', '6.1798', '5.9164'] avg: 5.8645 seconds. Result: ('S', None, None)
- Version_4. Time: ['4.4515', '4.6273', '4.5575', '5.1038', '4.5690', '5.5867', '4.6190', '4.3742'] avg: 4.7361 seconds. Result: ('S', None, None)
- Version_5. Time: ['9.6293', '9.2506', '9.4853', '9.4888', '9.9770', '9.4279', '8.8197', '9.5834'] avg: 9.4578 seconds. Result: ('S', None, None)
- Version_6. Time: ['4.5230', '4.8430', '4.2102', '4.0092', '3.8857', '3.9922', '4.1602', '4.2422'] avg: 4.2332 seconds. Result: ('S', None, None)
- Version_7. Time: ['4.0883', '4.0243', '4.8108', '4.5759', '5.1481', '3.7471', '4.5689', '4.6826'] avg: 4.4557 seconds. Result: ('S', None, None)
- Version_8. Time: ['5.0614', '3.7932', '3.8564', '4.6010', '5.0058', '4.1369', '4.0251', '4.1000'] avg: 4.3225 seconds. Result: ('S', None, None)
- Version_9. Time: ['4.1771', '3.6974', '4.5696', '4.4082', '4.7066', '4.3997', '4.4996', '3.7673'] avg: 4.2782 seconds. Result: ('S', None, None)
Category: 'L-X'
- Version_1. Time: ['4.2172', '4.3915', '4.0843', '4.1412', '4.6535', '5.2083', '4.2126', '5.0775'] avg: 4.4983 seconds. Result: ('L', 'X', None)
- Version_2. Time: ['5.8182', '5.8701', '5.5157', '6.2043', '5.6811', '6.1205', '6.1630', '6.4713'] avg: 5.9805 seconds. Result: ('L', 'X', None)
- Version_3. Time: ['6.3933', '5.5967', '6.0748', '6.1568', '5.6402', '6.0237', '5.5000', '6.6540'] avg: 6.0049 seconds. Result: ('L', 'X', None)
- Version_4. Time: ['5.6102', '4.3341', '4.5073', '4.2920', '4.1078', '4.5111', '4.2617', '4.1340'] avg: 4.4698 seconds. Result: ('L', 'X', None)
- Version_5. Time: ['7.4919', '7.7767', '7.9382', '7.7996', '7.5830', '8.1363', '7.7707', '7.8842'] avg: 7.7976 seconds. Result: ('L', 'X', None)
- Version_6. Time: ['5.0023', '4.7793', '4.1707', '4.6574', '3.9778', '4.0796', '4.1567', '4.4596'] avg: 4.4104 seconds. Result: ('L', 'X', None)
- Version_7. Time: ['5.1885', '5.5000', '5.3212', '4.9124', '5.3089', '4.4967', '4.5273', '5.0567'] avg: 5.0390 seconds. Result: ('L', 'X', None)
- Version_8. Time: ['8.2324', '7.7573', '5.0447', '4.2837', '4.5465', '4.5858', '4.5212', '4.2890'] avg: 5.4076 seconds. Result: ('L', 'X', None)
- Version_9. Time: ['4.9617', '5.2727', '4.7976', '4.3926', '4.6490', '4.3392', '4.5718', '5.0948'] avg: 4.7599 seconds. Result: ('L', 'X', None)
Category: 'P-V-00'
- Version_1. Time: ['5.0327', '5.9343', '6.1939', '5.2602', '5.3118', '4.7386', '6.2540', '5.0834'] avg: 5.4761 seconds. Result: ('P', 'V', '00')
- Version_2. Time: ['5.6770', '6.6008', '6.8833', '6.6666', '6.6429', '6.5933', '6.1045', '5.8783'] avg: 6.3808 seconds. Result: ('P', 'V', '00')
- Version_3. Time: ['6.0329', '7.2731', '7.4313', '6.0923', '6.4224', '7.0072', '7.0789', '7.2216'] avg: 6.8200 seconds. Result: ('P', 'V', '00')
- Version_4. Time: ['5.6545', '5.3423', '5.8155', '6.0092', '6.1311', '5.3688', '5.5865', '6.3852'] avg: 5.7866 seconds. Result: ('P', 'V', '00')
- Version_5. Time: ['4.1053', '3.7350', '3.9594', '4.3712', '4.5153', '4.4951', '3.6372', '3.9929'] avg: 4.1014 seconds. Result: ('P', 'V', '00')
- Version_6. Time: ['5.8103', '4.7281', '5.4567', '4.9565', '4.3047', '5.2205', '4.8195', '4.9879'] avg: 5.0355 seconds. Result: ('P', 'V', '00')
- Version_7. Time: ['4.8960', '5.0647', '5.2317', '5.5005', '5.5057', '5.3730', '5.5888', '5.8619'] avg: 5.3778 seconds. Result: ('P', 'V', '00')
- Version_8. Time: ['6.5043', '6.4697', '6.3258', '6.2640', '6.0972', '6.7243', '6.0332', '6.1047'] avg: 6.3154 seconds. Result: ('P', 'V', '00')
- Version_9. Time: ['4.7985', '4.8328', '5.0163', '4.7270', '4.8832', '4.7644', '4.6239', '4.5375'] avg: 4.7730 seconds. Result: ('P', 'V', '00')
Category: 'P-V-01'
- Version_1. Time: ['5.5960', '5.6142', '4.8452', '5.1641', '5.6640', '5.4405', '5.5061', '5.3999'] avg: 5.4038 seconds. Result: ('P', 'V', '01')
- Version_2. Time: ['6.6395', '6.1817', '5.9204', '6.6769', '6.2221', '6.0670', '6.2720', '7.1706'] avg: 6.3938 seconds. Result: ('P', 'V', '01')
- Version_3. Time: ['6.7438', '5.9112', '6.2280', '6.2494', '6.2941', '6.4551', '6.2541', '6.4263'] avg: 6.3203 seconds. Result: ('P', 'V', '01')
- Version_4. Time: ['5.9702', '5.2564', '5.9222', '5.4209', '4.8554', '5.8894', '5.2635', '5.9574'] avg: 5.5669 seconds. Result: ('P', 'V', '01')
- Version_5. Time: ['3.9473', '3.8750', '3.7272', '3.7373', '4.3558', '4.5179', '4.5860', '4.4242'] avg: 4.1464 seconds. Result: ('P', 'V', '01')
- Version_6. Time: ['4.7086', '4.2876', '5.0586', '4.9158', '4.5456', '5.5506', '4.8864', '5.2585'] avg: 4.9015 seconds. Result: ('P', 'V', '01')
- Version_7. Time: ['4.6604', '4.7461', '5.1198', '5.0982', '5.5934', '4.8209', '4.8486', '4.6351'] avg: 4.9403 seconds. Result: ('P', 'V', '01')
- Version_8. Time: ['6.3933', '5.9582', '6.7649', '5.7215', '6.3356', '6.0045', '6.7154', '5.9245'] avg: 6.2273 seconds. Result: ('P', 'V', '01')
- Version_9. Time: ['5.0991', '4.2702', '5.1329', '4.8204', '5.6348', '5.5667', '5.1669', '5.5726'] avg: 5.1579 seconds. Result: ('P', 'V', '01')
Category: 'L-X-A-B-C-D'
- Version_1. Time: ['5.7097', '5.5008', '5.3173', '6.4196', '6.0106', '5.9461', '5.6574', '5.5792'] avg: 5.7676 seconds. Result: ('L', 'X', 'A')
- Version_2. Time: ['6.9327', '5.9453', '5.8657', '5.9501', '6.6431', '6.8088', '6.3981', '6.9031'] avg: 6.4309 seconds. Result: ('L', 'X', 'A')
- Version_3. Time: ['6.1899', '6.4949', '7.0226', '6.0464', '6.2733', '6.4704', '6.2042', '7.0923'] avg: 6.4742 seconds. Result: ('L', 'X', 'A')
- Version_4. Time: ['6.3624', '7.0440', '5.7504', '6.1171', '7.7202', '5.6763', '5.0190', '5.5107'] avg: 6.1500 seconds. Result: ('L', 'X', 'A')
- Version_5. Time: ['5.1114', '4.4265', '4.6301', '4.3467', '3.8769', '4.0600', '3.8377', '4.0686'] avg: 4.2948 seconds. Result: ('L', 'X', 'A')
- Version_6. Time: ['5.2917', '5.5497', '5.2394', '5.3047', '4.7493', '4.7868', '4.8223', '5.3767'] avg: 5.1401 seconds. Result: ('L', 'X', 'A')
- Version_7. Time: ['5.2628', '5.6313', '5.6360', '5.4865', '5.2707', '5.4345', '5.5850', '5.0654'] avg: 5.4215 seconds. Result: ('L', 'X', 'A')
- Version_8. Time: ['6.0642', '5.6462', '6.0626', '6.5773', '7.5202', '6.2827', '6.1967', '5.9496'] avg: 6.2874 seconds. Result: ('L', 'X', 'A')
- Version_9. Time: ['5.4105', '4.9328', '5.0816', '5.6080', '5.6783', '6.7347', '5.0828', '5.1962'] avg: 5.4656 seconds. Result: ('L', 'X', 'A')
Saved results to: performance_comparison.png
Press Enter to exit...
"""

Немає коментарів:

Коли забув ти рідну мову, біднієш духом ти щодня...
When you forgot your native language you would become a poor at spirit every day ...

Д.Білоус / D.Bilous
Рабів до раю не пускають. Будь вільним!

ipv6 ready