sysinfo.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import os
  2. import psutil
  3. from utils.log.trans_log import trans_print
  4. def get_cpu_count():
  5. return psutil.cpu_count()
  6. def get_available_cpu_count_with_percent(percent: float = 1):
  7. cpu_count = get_cpu_count()
  8. return int(cpu_count * percent)
  9. def get_file_size(file_path):
  10. return os.path.getsize(file_path)
  11. def get_available_memory_with_percent(percent: float = 1):
  12. memory_info = psutil.virtual_memory()
  13. return int(memory_info.available * percent)
  14. def get_max_file_size(file_paths: list[str]):
  15. max_size = 0
  16. for file_path in file_paths:
  17. file_size = get_file_size(file_path)
  18. if file_size > max_size:
  19. max_size = file_size
  20. return max_size
  21. def use_files_get_max_cpu_count(file_paths: list[str], memory_percent: float = 1 / 6, cpu_percent: float = 2 / 5):
  22. max_file_size = get_max_file_size(file_paths)
  23. free_memory = get_available_memory_with_percent(memory_percent)
  24. count = int(free_memory / max_file_size)
  25. max_cpu_count = get_available_cpu_count_with_percent(cpu_percent)
  26. result = count if count <= max_cpu_count else max_cpu_count
  27. if result == 0:
  28. result = 1
  29. trans_print("总文件数:", len(file_paths), ",获取最大文件大小:", str(round(max_file_size / 2 ** 20, 2)) + "M",
  30. "可用内存:", str(get_available_memory_with_percent(1) / 2 ** 20) + "M",
  31. "总CPU数:", get_cpu_count(), "CPU使用比例:", round(cpu_percent, 2), "CPU可用数量:", max_cpu_count,
  32. ",最终确定使用进程数:", result)
  33. return result
  34. if __name__ == '__main__':
  35. from utils.file.trans_methods import read_files
  36. import datetime
  37. read_path = r"Z:\collection_data\1进行中\密马风电场-山西-大唐\收资数据\scada\秒级数据"
  38. begin = datetime.datetime.now()
  39. all_files = read_files(read_path)
  40. print(datetime.datetime.now() - begin)
  41. print(use_files_get_max_cpu_count(all_files))
  42. print(get_available_memory_with_percent(1) / 2 ** 20)
  43. print(get_available_memory_with_percent(2 / 3) / 2 ** 20)
  44. begin = datetime.datetime.now()
  45. print(len(all_files))
  46. print(get_max_file_size(all_files) / 2 ** 20)
  47. print(datetime.datetime.now() - begin)