1 /* 2 DSFML - The Simple and Fast Multimedia Library for D 3 4 Copyright (c) 2013 - 2015 Jeremy DeHaan (dehaan.jeremiah@gmail.com) 5 6 This software is provided 'as-is', without any express or implied warranty. 7 In no event will the authors be held liable for any damages arising from the use of this software. 8 9 Permission is granted to anyone to use this software for any purpose, including commercial applications, 10 and to alter it and redistribute it freely, subject to the following restrictions: 11 12 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. 13 If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 14 15 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 16 17 3. This notice may not be removed or altered from any source distribution 18 */ 19 20 ///A module containing the Clock class. 21 module dsfml.system.clock; 22 23 public import core.time; 24 25 /** 26 *Utility class that measures the elapsed time. 27 * 28 *Clock is a lightweight class for measuring time. 29 * 30 *Its provides the most precise time that the underlying OS can achieve (generally microseconds or nanoseconds). 31 *It also ensures monotonicity, which means that the returned time can never go backward, even if the system time is changed. 32 */ 33 class Clock 34 { 35 static if(__VERSION__ < 2067L) 36 { 37 alias MonoTime = TickDuration; 38 alias currTime = TickDuration.currSystemTick; 39 } 40 else 41 { 42 alias currTime = MonoTime.currTime; 43 } 44 45 package MonoTime m_startTime; 46 47 ///Default constructor. 48 this() 49 { 50 m_startTime = currTime; 51 } 52 53 ///Destructor 54 ~this() 55 { 56 import dsfml.system.config; 57 mixin(destructorOutput); 58 } 59 60 ///Get the elapsed time. 61 /// 62 ///This function returns the time elapsed since the last call to restart() (or the construction of the instance if restart() has not been called). 63 /// 64 ///Returns: Time elapsed . 65 Duration getElapsedTime() const 66 { 67 return cast(Duration)(currTime - m_startTime); 68 } 69 70 ///Restart the clock. 71 /// 72 ///This function puts the time counter back to zero. It also returns the time elapsed since the clock was started. 73 /// 74 ///Returns: Time elapsed. 75 Duration restart() 76 { 77 MonoTime now = currTime; 78 auto elapsed = now - m_startTime; 79 m_startTime = now; 80 81 return cast(Duration)elapsed; 82 } 83 84 } 85 86 unittest 87 { 88 version(DSFML_Unittest_System) 89 { 90 import std.stdio; 91 import dsfml.system.sleep; 92 import std.math; 93 94 writeln("Unit test for Clock"); 95 96 Clock clock = new Clock(); 97 98 writeln("Counting Time for 5 seconds.(rounded to nearest second)"); 99 100 while(clock.getElapsedTime().total!"seconds" < 5) 101 { 102 writeln(clock.getElapsedTime().total!"seconds"); 103 sleep(seconds(1)); 104 } 105 106 writeln(); 107 } 108 }