From 4576a80954d57bf2cb8ab3d99b73b75b84b2ce02 Mon Sep 17 00:00:00 2001
From: tom barrett <spalf0@gmail.com>
Date: Fri, 29 Mar 2019 08:52:08 -0500
Subject: more consistent loop durations

---
 src/bin/server.rs | 10 ++++++++--
 src/constants.rs  |  2 +-
 2 files changed, 9 insertions(+), 3 deletions(-)

diff --git a/src/bin/server.rs b/src/bin/server.rs
index e8fa735..881cc4d 100644
--- a/src/bin/server.rs
+++ b/src/bin/server.rs
@@ -4,7 +4,7 @@ use std::collections::HashMap;
 use std::io::Write;
 use std::net::TcpListener;
 use std::thread::sleep;
-use std::time::Duration;
+use std::time::{Duration, Instant};
 
 use space::constants;
 use space::mass::Mass;
@@ -42,6 +42,8 @@ fn main() {
                 connections.push(new_connection);
             }
             _ => {
+                let timer = Instant::now();
+
                 for connection in &mut connections {
                     if connection.open {
                         let mut ship = masses.remove(&connection.name).unwrap();
@@ -62,7 +64,11 @@ fn main() {
                     masses.insert(key.to_string(), mass);
                 }
 
-                sleep(Duration::from_millis(constants::SLEEP_DURATION));
+                if timer.elapsed().as_millis() < constants::LOOP_DURATION_MS.into() {
+                    sleep(Duration::from_millis(
+                        constants::LOOP_DURATION_MS - timer.elapsed().as_millis() as u64,
+                    ));
+                }
             }
         }
     }
diff --git a/src/constants.rs b/src/constants.rs
index ad73b19..ab045bf 100644
--- a/src/constants.rs
+++ b/src/constants.rs
@@ -27,8 +27,8 @@ pub const IRON_SIZE: usize = 1;
 pub const HYDROGEN_SIZE: usize = 1;
 pub const CRUDE_MINERALS_SIZE: usize = 10;
 
-pub const SLEEP_DURATION: u64 = 100;
 pub const FLOAT_PRECISION: f64 = 0.001;
+pub const LOOP_DURATION_MS: u64 = 100;
 
 pub const POSTGRES_USERNAME: &str = "space";
 pub const POSTGRES_PASSWORD: &str = "space";
-- 
cgit v1.2.3