Skip to content

Commit

Permalink
refactor(discord-client.c): use µseconds in event loop instead of ms
Browse files Browse the repository at this point in the history
  • Loading branch information
Anotra committed Apr 15, 2022
1 parent 4ac8816 commit 1fc1432
Showing 1 changed file with 25 additions and 14 deletions.
39 changes: 25 additions & 14 deletions src/discord-client.c
Original file line number Diff line number Diff line change
Expand Up @@ -348,26 +348,37 @@ discord_run(struct discord *client)
while (1) {
if (CCORD_OK != (code = discord_gateway_start(&client->gw))) break;

next_run = (int64_t)cog_timestamp_ms();
next_run = (int64_t)discord_timestamp_us(client);
while (1) {
int poll_time = 0, poll_result;

now = (int64_t)cog_timestamp_ms();

if (!client->on_idle)
poll_time = now < next_run ? (int)(next_run - now) : 0;
now = (int64_t)discord_timestamp_us(client);

struct discord_timers *const timers[] =
{ &client->timers.internal, &client->timers.user };
for (unsigned i = 0; i < sizeof timers / sizeof *timers; i++) {
int64_t trigger_us, trigger_ms;
if (priority_queue_peek(timers[i]->q, &trigger_us, NULL)) {
trigger_ms = trigger_us / 1000;
if (trigger_us >= 0) {
if (trigger_ms <= now) {

if (!client->on_idle) {
poll_time = now < next_run ? (int)((next_run - now) / 1000) : 0;

for (unsigned i = 0; i < sizeof timers / sizeof *timers; i++) {
int64_t trigger;
if (priority_queue_peek(timers[i]->q, &trigger, NULL)) {
if (trigger < 0)
continue;
if (trigger <= now) {
poll_time = 0;
} else if (trigger_ms - now < poll_time) {
poll_time = (int)(trigger_ms - now);
}
else {
const int64_t next_timer = trigger - now;
if (next_timer < 3000 /* 3 milliseconds */) {
poll_time = 1; // FIXME: with below

// TODO: cog_sleep_us(next_timer);ddd
// poll_time = 0;
}
else {
poll_time = (int)((trigger - now) / 1000);
}
}
}
}
Expand Down Expand Up @@ -398,7 +409,7 @@ discord_run(struct discord *client)
break;

/* enforce a min 1 sec delay between runs */
next_run = now + 1000;
next_run = now + 1000000;
}
}

Expand Down

0 comments on commit 1fc1432

Please sign in to comment.