Created
May 8, 2019 15:18
-
-
Save kgutwin/1e0c8f60ffa59ac8c282dc336dfe6f5d to your computer and use it in GitHub Desktop.
Terminal latency meter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import math | |
import time | |
import curses | |
def median(lst): | |
n = len(lst) | |
if n < 1: | |
return None | |
if n % 2 == 1: | |
return sorted(lst)[n//2] | |
else: | |
return sum(sorted(lst)[n//2-1:n//2+1])/2.0 | |
def main(stdscr): | |
curses.curs_set(0) | |
stdscr.nodelay(1) | |
stdscr.leaveok(1) | |
stdscr.addstr(1, 1, "Terminal Latency Meter ----------------------------") | |
stdscr.addstr(2, 1, " - Press spacebar in time with the flashing light") | |
stdscr.addstr(3, 1, " - Press q to exit") | |
running = True | |
key_latencies = [] | |
key_latency_cut = 0 | |
while running: | |
b = int(time.time()) % 2 and "#" or " " | |
for i in range(3): | |
stdscr.addstr(10 + i, 20, b * 3) | |
display_point = time.time() | |
display_latency = (display_point % 1.0) * 1000 | |
stdscr.addstr(16, 10, "Display latency: %8.3f ms" % display_latency) | |
if key_latencies: | |
stdscr.addstr(17, 14, "Key latency: %8.3f ms" % key_latencies[-1]) | |
avg_latency = sum(key_latencies) / len(key_latencies) | |
med_latency = median(key_latencies) | |
stdscr.addstr(18, 14, " Average: %8.3f ms" % avg_latency) | |
stdscr.addstr(19, 14, " Median: %8.3f ms" % med_latency) | |
stdscr.refresh() | |
next_refresh = math.ceil(time.time()) | |
while running: | |
if time.time() >= next_refresh: | |
break | |
try: | |
c = stdscr.getkey() | |
except curses.error: | |
c = '' | |
if c == 'q': | |
running = False | |
elif c == 'TIMEOUT': | |
break | |
if c == ' ' and time.time() > key_latency_cut: | |
bright_point = display_point | |
if b == ' ': | |
bright_point += 1.0 | |
key_latencies.append((time.time() - bright_point) * 1000) | |
key_latency_cut = time.time() + 1.5 | |
curses.wrapper(main) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment