1# Copyright 2015 The Chromium OS Authors. All rights reserved. 2# Use of this source code is governed by a BSD-style license that can be 3# found in the LICENSE file. 4 5import csv 6import logging 7import os 8import time 9 10from autotest_lib.client.bin import site_utils 11from autotest_lib.client.bin import test 12from autotest_lib.client.bin import utils 13 14# Measurement duration [seconds] for one interation. 15MEASUREMENT_DURATION = 10 16 17TERMINATE_PATH = "/tmp/terminate" 18 19# Time for initial test setup [seconds]. 20STABILIZATION_DURATION = 60 21 22PERF_RESULT_FILE = '/tmp/perf.csv' 23 24class performance_Tracker(test.test): 25 """Monitors cpu/memory usage.""" 26 27 version = 1 28 29 def get_cpu_usage(self): 30 """Computes current cpu usage in percentage. 31 32 @returns percentage cpu used as a float. 33 34 """ 35 cpu_usage_start = site_utils.get_cpu_usage() 36 time.sleep(MEASUREMENT_DURATION) 37 cpu_usage_end = site_utils.get_cpu_usage() 38 return site_utils.compute_active_cpu_time(cpu_usage_start, 39 cpu_usage_end) * 100 40 41 42 def used_mem(self): 43 """Computes used memory in percentage. 44 45 @returns percentage memory used as a float. 46 47 """ 48 total_memory = site_utils.get_mem_total() 49 return (total_memory - site_utils.get_mem_free()) * 100 / total_memory 50 51 52 def run_once(self): 53 if os.path.isfile(TERMINATE_PATH): 54 os.remove(TERMINATE_PATH) 55 56 time.sleep(STABILIZATION_DURATION) 57 perf_keyval = {} 58 perf_file = open(PERF_RESULT_FILE, 'w') 59 writer = csv.writer(perf_file) 60 writer.writerow(['cpu', 'memory']) 61 while True: 62 # This test runs forever until the terminate file is created. 63 if os.path.isfile(TERMINATE_PATH): 64 logging.info('Exit flag detected; exiting.') 65 perf_file.close() 66 return 67 perf_keyval['cpu_usage'] = self.get_cpu_usage() 68 perf_keyval['memory_usage'] = self.used_mem() 69 writer.writerow([perf_keyval['cpu_usage'], 70 perf_keyval['memory_usage']]) 71 self.write_perf_keyval(perf_keyval) 72 time.sleep(MEASUREMENT_DURATION) 73 perf_file.close() 74 75 76 def cleanup(self): 77 # cleanup() is run by common_lib/test.py. 78 if os.path.isfile(TERMINATE_PATH): 79 os.remove(TERMINATE_PATH) 80