Skip to content

Commit

Permalink
ttyplot.c: Call gettimeofday only once per loop
Browse files Browse the repository at this point in the history
  • Loading branch information
hartwork committed Dec 2, 2023
1 parent 0da4ce8 commit 4554d37
Showing 1 changed file with 16 additions and 11 deletions.
27 changes: 16 additions & 11 deletions ttyplot.c
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,7 @@ int main(int argc, char *argv[]) {
int i;
bool stdin_is_open = true;
time_t prev_paint_at_seconds = 0;
long timeout_nanos = 0;
int cached_opterr;
const char *optstring = "2rc:e:E:s:m:M:t:u:vh";
int show_ver;
Expand Down Expand Up @@ -613,17 +614,6 @@ int main(int argc, char *argv[]) {
select_nfds = tty + 1;
}

// Determine how long we can allow `select` to sleep. The rules are:
// 1. If we find the system clock has already advanced on seconds level,
// there should be no delay, we should get the clock redrawn asap.
// 2. Otherwise wait (more or less) exactly until the system clock
// has advanced, only then redraw the clock.
gettimeofday(&now, NULL);
int timeout_nanos = 0;
if (now.tv_sec == prev_paint_at_seconds) {
const suseconds_t microseconds_until_full_second = 1000 * 1000 - now.tv_usec;
timeout_nanos = 1000 * microseconds_until_full_second;
}
struct timespec timeout = {
.tv_sec = 0,
.tv_nsec = timeout_nanos
Expand Down Expand Up @@ -666,6 +656,21 @@ int main(int argc, char *argv[]) {

gettimeofday(&now, NULL); // for input handling and also drawing

// Determine how long we can allow the next call to `select` to sleep.
// The rules are:
// 1. If we find the system clock has already advanced on seconds level,
// there should be no delay, we should get the clock redrawn asap.
// 2. Otherwise wait (more or less) exactly until the system clock
// has advanced, only then redraw the clock.
// 3. Consider input handling and drawing fast enough to be ignored
// altogether. That's Edgar's idea, Sebastian doesn't like it at all :)
if (now.tv_sec == prev_paint_at_seconds) {
const suseconds_t microseconds_until_full_second = 1000 * 1000 - now.tv_usec;
timeout_nanos = 1000 * microseconds_until_full_second;
} else {
timeout_nanos = 0;
}

// Handle input data.
if (select_ret > 0 && FD_ISSET(STDIN_FILENO, &read_fds)) {
bool input_closed = handle_input_event();
Expand Down

0 comments on commit 4554d37

Please sign in to comment.