Merge branch 'no-unittest-dep' of https://github.com/parallel-fs-utils/fio
[fio.git] / tools / hist / fio-histo-log-pctiles.py
CommitLineData
d8296fdd
BE
1#!/usr/bin/env python
2
3# module to parse fio histogram log files, not using pandas
4# runs in python v2 or v3
5# to get help with the CLI: $ python fio-histo-log-pctiles.py -h
6# this can be run standalone as a script but is callable
7# assumes all threads run for same time duration
8# assumes all threads are doing the same thing for the entire run
9
10# percentiles:
11# 0 - min latency
12# 50 - median
13# 100 - max latency
14
15# TO-DO:
16# separate read and write stats for randrw mixed workload
17# report average latency if needed
18# prove that it works (partially done with unit tests)
19
20# to run unit tests, set UNITTEST environment variable to anything
21# if you do this, don't pass normal CLI parameters to it
22# otherwise it runs the CLI
23
24import sys, os, math, copy
25from copy import deepcopy
c670cb44 26import argparse
088a092e
BE
27
28unittest2_imported = True
29try:
30 import unittest2
31except ImportError:
32 unittest2_imported = False
d8296fdd
BE
33
34msec_per_sec = 1000
35nsec_per_usec = 1000
36
37class FioHistoLogExc(Exception):
38 pass
39
c670cb44 40# if there is an error, print message, and exit with error status
d8296fdd 41
c670cb44 42def myabort(msg):
d8296fdd 43 print('ERROR: ' + msg)
d8296fdd
BE
44 sys.exit(1)
45
d8296fdd
BE
46# convert histogram log file into a list of
47# (time_ms, direction, bsz, buckets) tuples where
48# - time_ms is the time in msec at which the log record was written
49# - direction is 0 (read) or 1 (write)
50# - bsz is block size (not used)
51# - buckets is a CSV list of counters that make up the histogram
52# caller decides if the expected number of counters are present
53
54
55def exception_suffix( record_num, pathname ):
56 return 'in histogram record %d file %s' % (record_num+1, pathname)
57
58# log file parser raises FioHistoLogExc exceptions
59# it returns histogram buckets in whatever unit fio uses
60
61def parse_hist_file(logfn, buckets_per_interval):
62 max_timestamp_ms = 0.0
63
64 with open(logfn, 'r') as f:
65 records = [ l.strip() for l in f.readlines() ]
66 intervals = []
67 for k, r in enumerate(records):
68 if r == '':
69 continue
70 tokens = r.split(',')
71 try:
72 int_tokens = [ int(t) for t in tokens ]
73 except ValueError as e:
74 raise FioHistoLogExc('non-integer value %s' % exception_suffix(k+1, logfn))
75
76 neg_ints = list(filter( lambda tk : tk < 0, int_tokens ))
77 if len(neg_ints) > 0:
78 raise FioHistoLogExc('negative integer value %s' % exception_suffix(k+1, logfn))
79
80 if len(int_tokens) < 3:
81 raise FioHistoLogExc('too few numbers %s' % exception_suffix(k+1, logfn))
82
83 time_ms = int_tokens[0]
84 if time_ms > max_timestamp_ms:
85 max_timestamp_ms = time_ms
86
87 direction = int_tokens[1]
88 if direction != 0 and direction != 1:
89 raise FioHistoLogExc('invalid I/O direction %s' % exception_suffix(k+1, logfn))
90
91 bsz = int_tokens[2]
92 if bsz > (1 << 24):
93 raise FioHistoLogExc('block size too large %s' % exception_suffix(k+1, logfn))
94
95 buckets = int_tokens[3:]
96 if len(buckets) != buckets_per_interval:
97 raise FioHistoLogExc('%d buckets per interval but %d expected in %s' %
98 (len(buckets), buckets_per_interval, exception_suffix(k+1, logfn)))
99 intervals.append((time_ms, direction, bsz, buckets))
100 if len(intervals) == 0:
101 raise FioHistoLogExc('no records in %s' % logfn)
102 return (intervals, max_timestamp_ms)
103
104
105# compute time range for each bucket index in histogram record
106# see comments in https://github.com/axboe/fio/blob/master/stat.h
107# for description of bucket groups and buckets
108# fio v3 bucket ranges are in nanosec (since response times are measured in nanosec)
109# but we convert fio v3 nanosecs to floating-point microseconds
110
111def time_ranges(groups, counters_per_group, fio_version=3):
112 bucket_width = 1
113 bucket_base = 0
114 bucket_intervals = []
115 for g in range(0, groups):
116 for b in range(0, counters_per_group):
117 rmin = float(bucket_base)
118 rmax = rmin + bucket_width
119 if fio_version == 3:
120 rmin /= nsec_per_usec
121 rmax /= nsec_per_usec
122 bucket_intervals.append( [rmin, rmax] )
123 bucket_base += bucket_width
124 if g != 0:
125 bucket_width *= 2
126 return bucket_intervals
127
128
129# compute number of time quantum intervals in the test
130
131def get_time_intervals(time_quantum, max_timestamp_ms):
132 # round down to nearest second
133 max_timestamp = max_timestamp_ms // msec_per_sec
134 # round up to nearest whole multiple of time_quantum
135 time_interval_count = (max_timestamp + time_quantum) // time_quantum
136 end_time = time_interval_count * time_quantum
137 return (end_time, time_interval_count)
138
139# align raw histogram log data to time quantum so
140# we can then combine histograms from different threads with addition
141# for randrw workload we count both reads and writes in same output bucket
142# but we separate reads and writes for purposes of calculating
143# end time for histogram record.
144# this requires us to weight a raw histogram bucket by the
145# fraction of time quantum that the bucket overlaps the current
146# time quantum interval
147# for example, if we have a bucket with 515 samples for time interval
148# [ 1010, 2014 ] msec since start of test, and time quantum is 1 sec, then
149# for time quantum interval [ 1000, 2000 ] msec, the overlap is
150# (2000 - 1010) / (2000 - 1000) = 0.99
151# so the contribution of this bucket to this time quantum is
152# 515 x 0.99 = 509.85
153
154def align_histo_log(raw_histogram_log, time_quantum, bucket_count, max_timestamp_ms):
155
156 # slice up test time int intervals of time_quantum seconds
157
158 (end_time, time_interval_count) = get_time_intervals(time_quantum, max_timestamp_ms)
159 time_qtm_ms = time_quantum * msec_per_sec
160 end_time_ms = end_time * msec_per_sec
161 aligned_intervals = []
162 for j in range(0, time_interval_count):
163 aligned_intervals.append((
164 j * time_qtm_ms,
165 [ 0.0 for j in range(0, bucket_count) ] ))
166
167 log_record_count = len(raw_histogram_log)
168 for k, record in enumerate(raw_histogram_log):
169
170 # find next record with same direction to get end-time
171 # have to avoid going past end of array
172 # for fio randrw workload,
173 # we have read and write records on same time interval
174 # sometimes read and write records are in opposite order
175 # assertion checks that next read/write record
176 # can be separated by at most 2 other records
177
178 (time_msec, direction, sz, interval_buckets) = record
179 if k+1 < log_record_count:
180 (time_msec_end, direction2, _, _) = raw_histogram_log[k+1]
181 if direction2 != direction:
182 if k+2 < log_record_count:
183 (time_msec_end, direction2, _, _) = raw_histogram_log[k+2]
184 if direction2 != direction:
185 if k+3 < log_record_count:
186 (time_msec_end, direction2, _, _) = raw_histogram_log[k+3]
187 assert direction2 == direction
188 else:
189 time_msec_end = end_time_ms
190 else:
191 time_msec_end = end_time_ms
192 else:
193 time_msec_end = end_time_ms
194
195 # calculate first quantum that overlaps this histogram record
196
197 qtm_start_ms = (time_msec // time_qtm_ms) * time_qtm_ms
198 qtm_end_ms = ((time_msec + time_qtm_ms) // time_qtm_ms) * time_qtm_ms
199 qtm_index = qtm_start_ms // time_qtm_ms
200
201 # for each quantum that overlaps this histogram record's time interval
202
203 while qtm_start_ms < time_msec_end: # while quantum overlaps record
204
205 # calculate fraction of time that this quantum
206 # overlaps histogram record's time interval
207
208 overlap_start = max(qtm_start_ms, time_msec)
209 overlap_end = min(qtm_end_ms, time_msec_end)
210 weight = float(overlap_end - overlap_start)
211 weight /= (time_msec_end - time_msec)
212 (_,aligned_histogram) = aligned_intervals[qtm_index]
213 for bx, b in enumerate(interval_buckets):
214 weighted_bucket = weight * b
215 aligned_histogram[bx] += weighted_bucket
216
217 # advance to the next time quantum
218
219 qtm_start_ms += time_qtm_ms
220 qtm_end_ms += time_qtm_ms
221 qtm_index += 1
222
223 return aligned_intervals
224
225# add histogram in "source" to histogram in "target"
226# it is assumed that the 2 histograms are precisely time-aligned
227
228def add_to_histo_from( target, source ):
229 for b in range(0, len(source)):
230 target[b] += source[b]
231
232# compute percentiles
233# inputs:
234# buckets: histogram bucket array
235# wanted: list of floating-pt percentiles to calculate
236# time_ranges: [tmin,tmax) time interval for each bucket
237# returns None if no I/O reported.
238# otherwise we would be dividing by zero
239# think of buckets as probability distribution function
240# and this loop is integrating to get cumulative distribution function
241
242def get_pctiles(buckets, wanted, time_ranges):
243
244 # get total of IO requests done
245 total_ios = 0
246 for io_count in buckets:
247 total_ios += io_count
248
249 # don't return percentiles if no I/O was done during interval
250 if total_ios == 0.0:
251 return None
252
253 pctile_count = len(wanted)
254
255 # results returned as dictionary keyed by percentile
256 pctile_result = {}
257
258 # index of next percentile in list
259 pctile_index = 0
260
261 # next percentile
262 next_pctile = wanted[pctile_index]
263
264 # no one is interested in percentiles bigger than this but not 100.0
265 # this prevents floating-point error from preventing loop exit
266 almost_100 = 99.9999
267
0456267b
BE
268 # pct is the percentile corresponding to
269 # all I/O requests up through bucket b
270 pct = 0.0
d8296fdd
BE
271 total_so_far = 0
272 for b, io_count in enumerate(buckets):
0456267b
BE
273 if io_count == 0:
274 continue
d8296fdd 275 total_so_far += io_count
0456267b
BE
276 # last_pct_lt is the percentile corresponding to
277 # all I/O requests up to, but not including, bucket b
278 last_pct = pct
279 pct = 100.0 * float(total_so_far) / total_ios
d8296fdd
BE
280 # a single bucket could satisfy multiple pctiles
281 # so this must be a while loop
0456267b
BE
282 # for 100-percentile (max latency) case, no bucket exceeds it
283 # so we must stop there.
284 while ((next_pctile == 100.0 and pct >= almost_100) or
285 (next_pctile < 100.0 and pct > next_pctile)):
286 # interpolate between min and max time for bucket time interval
287 # we keep the time_ranges access inside this loop,
288 # even though it could be above the loop,
289 # because in many cases we will not be even entering
290 # the loop so we optimize out these accesses
d8296fdd 291 range_max_time = time_ranges[b][1]
0456267b
BE
292 range_min_time = time_ranges[b][0]
293 offset_frac = (next_pctile - last_pct)/(pct - last_pct)
294 interpolation = range_min_time + (offset_frac*(range_max_time - range_min_time))
295 pctile_result[next_pctile] = interpolation
d8296fdd
BE
296 pctile_index += 1
297 if pctile_index == pctile_count:
298 break
299 next_pctile = wanted[pctile_index]
300 if pctile_index == pctile_count:
301 break
302 assert pctile_index == pctile_count
303 return pctile_result
304
305
c670cb44 306# this is really the main program
d8296fdd 307
c670cb44
BE
308def compute_percentiles_from_logs():
309 parser = argparse.ArgumentParser()
310 parser.add_argument("--fio-version", dest="fio_version",
311 default="3", choices=[2,3], type=int,
312 help="fio version (default=3)")
313 parser.add_argument("--bucket-groups", dest="bucket_groups", default="29", type=int,
314 help="fio histogram bucket groups (default=29)")
315 parser.add_argument("--bucket-bits", dest="bucket_bits",
316 default="6", type=int,
317 help="fio histogram buckets-per-group bits (default=6 means 64 buckets/group)")
318 parser.add_argument("--percentiles", dest="pctiles_wanted",
4b34a0eb 319 default=[ 0., 50., 95., 99., 100.], type=float, nargs='+',
c670cb44
BE
320 help="fio histogram buckets-per-group bits (default=6 means 64 buckets/group)")
321 parser.add_argument("--time-quantum", dest="time_quantum",
322 default="1", type=int,
323 help="time quantum in seconds (default=1)")
324 parser.add_argument("--output-unit", dest="output_unit",
325 default="usec", type=str,
326 help="Latency percentile output unit: msec|usec|nsec (default usec)")
4b34a0eb
BE
327 parser.add_argument("file_list", nargs='+',
328 help='list of files, preceded by " -- " if necessary')
c670cb44 329 args = parser.parse_args()
c670cb44 330
4b34a0eb
BE
331 # default changes based on fio version
332 if args.fio_version == 2:
333 args.bucket_groups = 19
d8296fdd 334
c670cb44 335 # print parameters
d8296fdd 336
4b34a0eb 337 print('fio version = %d' % args.fio_version)
c670cb44
BE
338 print('bucket groups = %d' % args.bucket_groups)
339 print('bucket bits = %d' % args.bucket_bits)
340 print('time quantum = %d sec' % args.time_quantum)
341 print('percentiles = %s' % ','.join([ str(p) for p in args.pctiles_wanted ]))
342 buckets_per_group = 1 << args.bucket_bits
d8296fdd 343 print('buckets per group = %d' % buckets_per_group)
c670cb44 344 buckets_per_interval = buckets_per_group * args.bucket_groups
d8296fdd
BE
345 print('buckets per interval = %d ' % buckets_per_interval)
346 bucket_index_range = range(0, buckets_per_interval)
c670cb44
BE
347 if args.time_quantum == 0:
348 print('ERROR: time-quantum must be a positive number of seconds')
349 print('output unit = ' + args.output_unit)
350 if args.output_unit == 'msec':
d8296fdd 351 time_divisor = 1000.0
c670cb44 352 elif args.output_unit == 'usec':
d8296fdd
BE
353 time_divisor = 1.0
354
355 # calculate response time interval associated with each histogram bucket
356
c670cb44 357 bucket_times = time_ranges(args.bucket_groups, buckets_per_group, fio_version=args.fio_version)
d8296fdd
BE
358
359 # construct template for each histogram bucket array with buckets all zeroes
360 # we just copy this for each new histogram
361
362 zeroed_buckets = [ 0.0 for r in bucket_index_range ]
363
364 # print CSV header just like fiologparser_hist does
365
366 header = 'msec, '
c670cb44 367 for p in args.pctiles_wanted:
d8296fdd 368 header += '%3.1f, ' % p
c670cb44 369 print('time (millisec), percentiles in increasing order with values in ' + args.output_unit)
d8296fdd
BE
370 print(header)
371
372 # parse the histogram logs
373 # assumption: each bucket has a monotonically increasing time
374 # assumption: time ranges do not overlap for a single thread's records
375 # (exception: if randrw workload, then there is a read and a write
376 # record for the same time interval)
377
378 max_timestamp_all_logs = 0
379 hist_files = {}
c670cb44 380 for fn in args.file_list:
d8296fdd
BE
381 try:
382 (hist_files[fn], max_timestamp_ms) = parse_hist_file(fn, buckets_per_interval)
383 except FioHistoLogExc as e:
c670cb44 384 myabort(str(e))
d8296fdd
BE
385 max_timestamp_all_logs = max(max_timestamp_all_logs, max_timestamp_ms)
386
c670cb44
BE
387 (end_time, time_interval_count) = get_time_intervals(args.time_quantum, max_timestamp_all_logs)
388 all_threads_histograms = [ ((j*args.time_quantum*msec_per_sec), deepcopy(zeroed_buckets))
d8296fdd
BE
389 for j in range(0, time_interval_count) ]
390
391 for logfn in hist_files.keys():
392 aligned_per_thread = align_histo_log(hist_files[logfn],
c670cb44 393 args.time_quantum,
d8296fdd
BE
394 buckets_per_interval,
395 max_timestamp_all_logs)
396 for t in range(0, time_interval_count):
397 (_, all_threads_histo_t) = all_threads_histograms[t]
398 (_, log_histo_t) = aligned_per_thread[t]
d8296fdd
BE
399 add_to_histo_from( all_threads_histo_t, log_histo_t )
400
c670cb44
BE
401 # calculate percentiles across aggregate histogram for all threads
402
d8296fdd
BE
403 for (t_msec, all_threads_histo_t) in all_threads_histograms:
404 record = '%d, ' % t_msec
c670cb44 405 pct = get_pctiles(all_threads_histo_t, args.pctiles_wanted, bucket_times)
d8296fdd 406 if not pct:
c670cb44 407 for w in args.pctiles_wanted:
d8296fdd
BE
408 record += ', '
409 else:
410 pct_keys = [ k for k in pct.keys() ]
411 pct_values = [ str(pct[wanted]/time_divisor) for wanted in sorted(pct_keys) ]
412 record += ', '.join(pct_values)
413 print(record)
414
415
416
417#end of MAIN PROGRAM
418
419
d8296fdd
BE
420##### below are unit tests ##############
421
088a092e
BE
422if unittest2_imported:
423 import tempfile, shutil
424 from os.path import join
425 should_not_get_here = False
d8296fdd 426
088a092e 427 class Test(unittest2.TestCase):
d8296fdd
BE
428 tempdir = None
429
430 # a little less typing please
431 def A(self, boolean_val):
432 self.assertTrue(boolean_val)
433
434 # initialize unit test environment
435
436 @classmethod
437 def setUpClass(cls):
438 d = tempfile.mkdtemp()
439 Test.tempdir = d
440
441 # remove anything left by unit test environment
442 # unless user sets UNITTEST_LEAVE_FILES environment variable
443
444 @classmethod
445 def tearDownClass(cls):
446 if not os.getenv("UNITTEST_LEAVE_FILES"):
447 shutil.rmtree(cls.tempdir)
448
449 def setUp(self):
450 self.fn = join(Test.tempdir, self.id())
451
452 def test_a_add_histos(self):
453 a = [ 1.0, 2.0 ]
454 b = [ 1.5, 2.5 ]
455 add_to_histo_from( a, b )
456 self.A(a == [2.5, 4.5])
457 self.A(b == [1.5, 2.5])
458
459 def test_b1_parse_log(self):
460 with open(self.fn, 'w') as f:
461 f.write('1234, 0, 4096, 1, 2, 3, 4\n')
462 f.write('5678,1,16384,5,6,7,8 \n')
463 (raw_histo_log, max_timestamp) = parse_hist_file(self.fn, 4) # 4 buckets per interval
464 self.A(len(raw_histo_log) == 2 and max_timestamp == 5678)
465 (time_ms, direction, bsz, histo) = raw_histo_log[0]
466 self.A(time_ms == 1234 and direction == 0 and bsz == 4096 and histo == [ 1, 2, 3, 4 ])
467 (time_ms, direction, bsz, histo) = raw_histo_log[1]
468 self.A(time_ms == 5678 and direction == 1 and bsz == 16384 and histo == [ 5, 6, 7, 8 ])
469
470 def test_b2_parse_empty_log(self):
471 with open(self.fn, 'w') as f:
472 pass
473 try:
474 (raw_histo_log, max_timestamp_ms) = parse_hist_file(self.fn, 4)
475 self.A(should_not_get_here)
476 except FioHistoLogExc as e:
477 self.A(str(e).startswith('no records'))
478
479 def test_b3_parse_empty_records(self):
480 with open(self.fn, 'w') as f:
481 f.write('\n')
482 f.write('1234, 0, 4096, 1, 2, 3, 4\n')
483 f.write('5678,1,16384,5,6,7,8 \n')
484 f.write('\n')
485 (raw_histo_log, max_timestamp_ms) = parse_hist_file(self.fn, 4)
486 self.A(len(raw_histo_log) == 2 and max_timestamp_ms == 5678)
487 (time_ms, direction, bsz, histo) = raw_histo_log[0]
488 self.A(time_ms == 1234 and direction == 0 and bsz == 4096 and histo == [ 1, 2, 3, 4 ])
489 (time_ms, direction, bsz, histo) = raw_histo_log[1]
490 self.A(time_ms == 5678 and direction == 1 and bsz == 16384 and histo == [ 5, 6, 7, 8 ])
491
492 def test_b4_parse_non_int(self):
493 with open(self.fn, 'w') as f:
494 f.write('12, 0, 4096, 1a, 2, 3, 4\n')
495 try:
496 (raw_histo_log, _) = parse_hist_file(self.fn, 4)
497 self.A(False)
498 except FioHistoLogExc as e:
499 self.A(str(e).startswith('non-integer'))
500
501 def test_b5_parse_neg_int(self):
502 with open(self.fn, 'w') as f:
503 f.write('-12, 0, 4096, 1, 2, 3, 4\n')
504 try:
505 (raw_histo_log, _) = parse_hist_file(self.fn, 4)
506 self.A(False)
507 except FioHistoLogExc as e:
508 self.A(str(e).startswith('negative integer'))
509
510 def test_b6_parse_too_few_int(self):
511 with open(self.fn, 'w') as f:
512 f.write('0, 0\n')
513 try:
514 (raw_histo_log, _) = parse_hist_file(self.fn, 4)
515 self.A(False)
516 except FioHistoLogExc as e:
517 self.A(str(e).startswith('too few numbers'))
518
519 def test_b7_parse_invalid_direction(self):
520 with open(self.fn, 'w') as f:
521 f.write('100, 2, 4096, 1, 2, 3, 4\n')
522 try:
523 (raw_histo_log, _) = parse_hist_file(self.fn, 4)
524 self.A(False)
525 except FioHistoLogExc as e:
526 self.A(str(e).startswith('invalid I/O direction'))
527
528 def test_b8_parse_bsz_too_big(self):
529 with open(self.fn+'_good', 'w') as f:
530 f.write('100, 1, %d, 1, 2, 3, 4\n' % (1<<24))
531 (raw_histo_log, max_timestamp_ms) = parse_hist_file(self.fn+'_good', 4)
532 with open(self.fn+'_bad', 'w') as f:
533 f.write('100, 1, 20000000, 1, 2, 3, 4\n')
534 try:
535 (raw_histo_log, _) = parse_hist_file(self.fn+'_bad', 4)
536 self.A(False)
537 except FioHistoLogExc as e:
538 self.A(str(e).startswith('block size too large'))
539
540 def test_b9_parse_wrong_bucket_count(self):
541 with open(self.fn, 'w') as f:
542 f.write('100, 1, %d, 1, 2, 3, 4, 5\n' % (1<<24))
543 try:
544 (raw_histo_log, _) = parse_hist_file(self.fn, 4)
545 self.A(False)
546 except FioHistoLogExc as e:
547 self.A(str(e).__contains__('buckets per interval'))
548
549 def test_c1_time_ranges(self):
550 ranges = time_ranges(3, 2) # fio_version defaults to 3
551 expected_ranges = [ # fio_version 3 is in nanoseconds
552 [0.000, 0.001], [0.001, 0.002], # first group
553 [0.002, 0.003], [0.003, 0.004], # second group same width
554 [0.004, 0.006], [0.006, 0.008]] # subsequent groups double width
555 self.A(ranges == expected_ranges)
556 ranges = time_ranges(3, 2, fio_version=3)
557 self.A(ranges == expected_ranges)
558 ranges = time_ranges(3, 2, fio_version=2)
559 expected_ranges_v2 = [ [ 1000.0 * min_or_max for min_or_max in time_range ]
560 for time_range in expected_ranges ]
561 self.A(ranges == expected_ranges_v2)
562 # see fio V3 stat.h for why 29 groups and 2^6 buckets/group
563 normal_ranges_v3 = time_ranges(29, 64)
564 # for v3, bucket time intervals are measured in nanoseconds
565 self.A(len(normal_ranges_v3) == 29 * 64 and normal_ranges_v3[-1][1] == 64*(1<<(29-1))/1000.0)
566 normal_ranges_v2 = time_ranges(19, 64, fio_version=2)
567 # for v2, bucket time intervals are measured in microseconds so we have fewer buckets
568 self.A(len(normal_ranges_v2) == 19 * 64 and normal_ranges_v2[-1][1] == 64*(1<<(19-1)))
569
570 def test_d1_align_histo_log_1_quantum(self):
571 with open(self.fn, 'w') as f:
572 f.write('100, 1, 4096, 1, 2, 3, 4')
573 (raw_histo_log, max_timestamp_ms) = parse_hist_file(self.fn, 4)
574 self.A(max_timestamp_ms == 100)
575 aligned_log = align_histo_log(raw_histo_log, 5, 4, max_timestamp_ms)
576 self.A(len(aligned_log) == 1)
577 (time_ms0, h) = aligned_log[0]
578 self.A(time_ms0 == 0 and h == [1.0, 2.0, 3.0, 4.0])
579
580 # we need this to compare 2 lists of floating point numbers for equality
581 # because of floating-point imprecision
582
583 def compare_2_floats(self, x, y):
584 if x == 0.0 or y == 0.0:
585 return (x+y) < 0.0000001
586 else:
587 return (math.fabs(x-y)/x) < 0.00001
588
589 def is_close(self, buckets, buckets_expected):
590 if len(buckets) != len(buckets_expected):
591 return False
592 compare_buckets = lambda k: self.compare_2_floats(buckets[k], buckets_expected[k])
593 indices_close = list(filter(compare_buckets, range(0, len(buckets))))
594 return len(indices_close) == len(buckets)
595
596 def test_d2_align_histo_log_2_quantum(self):
597 with open(self.fn, 'w') as f:
598 f.write('2000, 1, 4096, 1, 2, 3, 4\n')
599 f.write('7000, 1, 4096, 1, 2, 3, 4\n')
600 (raw_histo_log, max_timestamp_ms) = parse_hist_file(self.fn, 4)
601 self.A(max_timestamp_ms == 7000)
602 (_, _, _, raw_buckets1) = raw_histo_log[0]
603 (_, _, _, raw_buckets2) = raw_histo_log[1]
604 aligned_log = align_histo_log(raw_histo_log, 5, 4, max_timestamp_ms)
605 self.A(len(aligned_log) == 2)
606 (time_ms1, h1) = aligned_log[0]
607 (time_ms2, h2) = aligned_log[1]
608 # because first record is from time interval [2000, 7000]
609 # we weight it according
610 expect1 = [float(b) * 0.6 for b in raw_buckets1]
611 expect2 = [float(b) * 0.4 for b in raw_buckets1]
612 for e in range(0, len(expect2)):
613 expect2[e] += raw_buckets2[e]
614 self.A(time_ms1 == 0 and self.is_close(h1, expect1))
615 self.A(time_ms2 == 5000 and self.is_close(h2, expect2))
616
0456267b
BE
617 # what to expect if histogram buckets are all equal
618 def test_e1_get_pctiles_flat_histo(self):
d8296fdd
BE
619 with open(self.fn, 'w') as f:
620 buckets = [ 100 for j in range(0, 128) ]
621 f.write('9000, 1, 4096, %s\n' % ', '.join([str(b) for b in buckets]))
622 (raw_histo_log, max_timestamp_ms) = parse_hist_file(self.fn, 128)
623 self.A(max_timestamp_ms == 9000)
624 aligned_log = align_histo_log(raw_histo_log, 5, 128, max_timestamp_ms)
625 time_intervals = time_ranges(4, 32)
626 # since buckets are all equal, then median is halfway through time_intervals
627 # and max latency interval is at end of time_intervals
628 self.A(time_intervals[64][1] == 0.066 and time_intervals[127][1] == 0.256)
629 pctiles_wanted = [ 0, 50, 100 ]
630 pct_vs_time = []
631 for (time_ms, histo) in aligned_log:
632 pct_vs_time.append(get_pctiles(histo, pctiles_wanted, time_intervals))
633 self.A(pct_vs_time[0] == None) # no I/O in this time interval
0456267b 634 expected_pctiles = { 0:0.000, 50:0.064, 100:0.256 }
d8296fdd
BE
635 self.A(pct_vs_time[1] == expected_pctiles)
636
0456267b
BE
637 # what to expect if just the highest histogram bucket is used
638 def test_e2_get_pctiles_highest_pct(self):
639 fio_v3_bucket_count = 29 * 64
640 with open(self.fn, 'w') as f:
641 # make a empty fio v3 histogram
642 buckets = [ 0 for j in range(0, fio_v3_bucket_count) ]
643 # add one I/O request to last bucket
644 buckets[-1] = 1
645 f.write('9000, 1, 4096, %s\n' % ', '.join([str(b) for b in buckets]))
646 (raw_histo_log, max_timestamp_ms) = parse_hist_file(self.fn, fio_v3_bucket_count)
647 self.A(max_timestamp_ms == 9000)
648 aligned_log = align_histo_log(raw_histo_log, 5, fio_v3_bucket_count, max_timestamp_ms)
649 (time_ms, histo) = aligned_log[1]
650 time_intervals = time_ranges(29, 64)
651 expected_pctiles = { 100.0:(64*(1<<28))/1000.0 }
652 pct = get_pctiles( histo, [ 100.0 ], time_intervals )
653 self.A(pct == expected_pctiles)
654
d8296fdd
BE
655# we are using this module as a standalone program
656
657if __name__ == '__main__':
658 if os.getenv('UNITTEST'):
088a092e
BE
659 if unittest2_imported:
660 sys.exit(unittest2.main())
661 else:
662 raise Exception('you must install unittest2 module to run unit test')
d8296fdd
BE
663 else:
664 compute_percentiles_from_logs()
665