Commit 6c3d4bf9 authored by Matthias Linhuber's avatar Matthias Linhuber
Browse files

Fix naming schema - now everything in snake_case

parent 95f226ad
......@@ -35,6 +35,21 @@ FILESIZES = {
}
def _generate_identifier():
""" Generates a unique ID for the measurement.
Based on the hostname and the current time/date
Returns
_______
str
unique identifier for current measurement
"""
datetime_now = datetime.now()
return str(platform.node()) + "_" + str(datetime_now)
class TestRun():
"""
Object that holds a set of test parameters which should be measured.
......@@ -42,14 +57,14 @@ class TestRun():
It uses `dd` to execute the test and stores the results.
"""
def __init__(self, bs, count, outfile='/tmp/test', repetitions=1):
self.bs: int = bs
def __init__(self, block_size, count, outfile='/tmp/test', repetitions=1):
self.block_size: int = block_size
self.count: int = count
self.outfile: str = outfile
self.repetitions: int = repetitions
self.testResults = []
self.test_results = []
def _executeDD(self):
def _execute_dd(self):
""" Executes `dd` with given parameters
This function could return incorrect values if the `dd` implementation
......@@ -60,15 +75,16 @@ class TestRun():
float
Output of the current `dd` command.
"""
print("Execute measurements with blocksize " + str(self.bs))
print("Execute measurements with blocksize " + str(self.block_size))
output = subprocess.run(
['dd', 'if=/dev/zero', 'of=' + self.outfile, 'bs=' +
str(self.bs), 'count=' + str(self.count)
], capture_output=True)
['dd', 'if=/dev/zero',
'of=' + self.outfile, 'bs=' + str(self.block_size),
'count=' + str(self.count)
], capture_output=True)
result = output.stderr.decode('utf-8')
if output.returncode != 0:
raise IOError("bs: " + str(self.bs) +
raise IOError("block_size: " + str(self.block_size) +
" - count: " + str(self.count))
result = result.splitlines()[-1:][0]
......@@ -83,23 +99,23 @@ class TestRun():
speed = transfered/time
return speed
def executeTest(self):
def execute_test(self):
for _ in range(self.repetitions):
measurement = self._executeDD()
self.testResults.append(measurement)
measurement = self._execute_dd()
self.test_results.append(measurement)
def getTestResults(self):
def get_rest_result(self):
"""Get the test results of all repetitions. Only populated after
`executeTest()` was called!
`execute_test()` was called!
Returns
----------
list
a list of floats : all test results. The list is #repetitions long.
"""
return self.testResults
return self.test_results
def getTestResutlAverage(self):
def get_test_result_average(self):
"""Calculate the average over all repetitions.
Returns
......@@ -107,31 +123,31 @@ class TestRun():
float
average of all test-restults
"""
return sum(self.testResults)/len(self.testResults)
return sum(self.test_results)/len(self.test_results)
def getFullPrintRepresentation(self,
numberFormatter,
showAllRepetitions=True):
def get_full_print_representation(self,
number_formatter,
print_all_repetitions=True):
r = [numberFormatter(self.bs, "B"),
numberFormatter(self.count, ""),
self.repetitions
]
rep = [number_formatter(self.block_size, "B"),
number_formatter(self.count, ""),
self.repetitions
]
if showAllRepetitions:
r.extend(list(map(numberFormatter, self.getTestResults())))
if print_all_repetitions:
rep.extend(list(map(number_formatter, self.get_rest_result())))
r.append(numberFormatter(self.getTestResutlAverage()))
return r
rep.append(number_formatter(self.get_test_result_average()))
return rep
def getJsonRepresentation(self):
def get_json_representation(self):
representation: dict = {}
representation["bs"] = self.bs
representation["block_size"] = self.block_size
representation["count"] = self.count
representation["representation"] = self.repetitions
representation["testResults"] = self.testResults
representation["average"] = self.getTestResutlAverage()
representation["test_results"] = self.test_results
representation["average"] = self.get_test_result_average()
return representation
......@@ -152,12 +168,12 @@ class ResultManager:
"""
self.testers = testers
self.repetitions = repetitions
self.jsonRepetition = {}
self.json_representation = {}
def printResults(self,
human=False,
table=True,
showAllRepetitions=True):
def print_results(self,
human=False,
table=True,
print_all_repetitions=True):
"""Prints the testresults to the command prompt.
Parameters:
......@@ -166,16 +182,16 @@ class ResultManager:
Transform raw byte values in human redable form yes/no
table: boolean
Output the results as table yes/no
showAllRepetitions: boolean
print_all_repetitions: boolean
Print all test results, or only print average over all repetions
"""
def humanReableTransofmer(num, suffix='B/s'):
def human_redable_formatter(num, suffix='B/s'):
""" Takes a number in and transforms it to human readable powerof 2
form e.g. (MiByte).
Example
humanReableTransofmer(2048) -> 2Ki
human_redable_formatter(2048) -> 2Ki
Taken from https://stackoverflow.com/a/1094933/5354060
......@@ -198,22 +214,22 @@ class ResultManager:
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix)
def indentiyFormatter(num, suffix="B/s"):
def identity_formatter(num, suffix="B/s"):
return str(num) + suffix
print()
print("Measured on " + self._generateIdentifier())
print("Measured on " + _generate_identifier())
if human:
formatter = humanReableTransofmer
formatter = human_redable_formatter
else:
formatter = indentiyFormatter
formatter = identity_formatter
results = [t.getFullPrintRepresentation(
formatter, showAllRepetitions) for t in self.testers]
results = [t.get_full_print_representation(
formatter, print_all_repetitions) for t in self.testers]
heading = ['Blocksize', 'Count', '#Repetitions']
if showAllRepetitions:
if print_all_repetitions:
heading.extend(["Run " + str(x) for x in range(self.repetitions)])
heading.append("Average")
......@@ -225,42 +241,28 @@ class ResultManager:
print(heading)
pprint(results)
def _generateIdentifier(self):
""" Generates a unique ID for the measurement.
Based on the hostname and the current time/date
Returns
_______
str
unique identifier for current measurement
"""
dateTimeObj = datetime.now()
return str(platform.node()) + "_" + str(dateTimeObj)
def _generateJsonRepresentation(self):
if len(self.jsonRepetition) == 0:
self.jsonRepetition = [x.getJsonRepresentation()
for x in self.testers]
def _generate_json_representation(self):
if len(self.json_representation) == 0:
self.json_representation = [x.get_json_representation()
for x in self.testers]
def exportJsonToFile(self, filename):
def export_json_to_file(self, filename):
if len(filename) == 0:
filename = self._generateIdentifier() + ".json"
filename = _generate_identifier() + ".json"
self._generateJsonRepresentation()
o = json.dumps(self.jsonRepetition, indent=4)
open(filename, "w").write(o)
self._generate_json_representation()
json_dump = json.dumps(self.json_representation, indent=4)
open(filename, "w").write(json_dump)
def printJson(self):
self._generateJsonRepresentation()
print(json.dumps(self.jsonRepetition, indent=4))
def print_json(self):
self._generate_json_representation()
print(json.dumps(self.json_representation, indent=4))
def executeAllTests(testers):
def execute_all_tests(testers):
for test in reversed(testers):
test.executeTest()
test.execute_test()
def main():
......@@ -272,7 +274,8 @@ def main():
parser.add_argument("--quick", "-q", action="store_true",
help='Measure predefined block sizes. See the --testValues for more info')
parser.add_argument("--repetitions", '-r', default=3,
type=int, help='Define number of measurement repetitions for each blocksize value')
type=int,
help='Define number of measurement repetitions for each blocksize value')
parser.add_argument("--fileSize", "--size", choices=FILESIZES.keys(),
help="Define desired fileSize for all parameter sets")
......@@ -311,15 +314,15 @@ def main():
if args.full or args.fileSize is not None:
if args.fileSize is None:
fileSizeExponent = 30
file_size_exponent = 30
else:
fileSizeExponent = FILESIZES[args.fileSize]
file_size_exponent = FILESIZES[args.fileSize]
testParams = [[2**(i), 2**(fileSizeExponent - i)]
for i in range(fileSizeExponent)
if i >= fileSizeExponent/2 or i >= 10]
test_parameters = [[2**(i), 2**(file_size_exponent - i)]
for i in range(file_size_exponent)
if i >= file_size_exponent/2 or i >= 10]
elif args.quick:
testParams = QUICK_TEST_PARAM_LIST
test_parameters = QUICK_TEST_PARAM_LIST
else:
print(parser.format_help())
......@@ -327,32 +330,32 @@ def main():
# Print testValues and exit program
if args.testValues:
pprint(testParams)
pprint(test_parameters)
return
# Generate TestRun Objects.
# Each object is populated with desired test parameters
testers = [TestRun(param[0], param[1], repetitions=args.repetitions)
for param in testParams]
for param in test_parameters]
# Execute all tests runners
executeAllTests(testers)
execute_all_tests(testers)
# Hadle Test data.
resultManager = ResultManager(testers, args.repetitions)
result_manager = ResultManager(testers, args.repetitions)
if args.json:
# Print JSON represetnation
resultManager.printJson()
result_manager.print_json()
else:
# Print Table representation
resultManager.printResults(human=args.human,
table=not args.json,
showAllRepetitions=not args.brief)
result_manager.print_results(human=args.human,
table=not args.json,
print_all_repetitions=not args.brief)
# Store test restult if desired by the user
if args.storeResult or len(args.outputFile) > 0:
resultManager.exportJsonToFile(args.outputFile)
result_manager.export_json_to_file(args.outputFile)
main()
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment