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