Scratchpad

If you are new to Scratchpad, and want full access as a Scratchpad editor, create an account!
If you already have an account, log in and have fun!!

READ MORE

Scratchpad
Advertisement

using System;
using System.Threading; 

namespace TimingTest
{ 
	/// <summary> 
	/// Summary description for Class1.
	/// </summary>
	class Class1
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			new Class1().start();
			Console.ReadLine();
		}

		private Boolean running = true;
		private int fpsCounter;
		private long fpsTime;
		private int fps;
		private int ups;
		private int upsCounter;
		
		/**
		 * This starts the loop.
		 */
		public void start()
		{
			printRuler();
			long delta;
			long lastLoopTime = DateTime.Now.Ticks;
			long elapsedTime = 0;
 			frameTime = 0;
			frameDuration = ticksPerSecond / targetFPS;	  	// time between renders  
			fpsTime = 0;
			updateTime = 0;

			while (running)
			{
				delta = DateTime.Now.Ticks - lastLoopTime;
				lastLoopTime += delta;
				elapsedTime += delta;
				fpsTime += delta;

				requestUpdate(delta);
				requestRender(delta);
			
				// stop the loop 
				if (elapsedTime > 100000000L)
					running = false;
			}
		}

		private static long ticksPerSecond = 10000000L;
		private static int targetFPS = 60;

		private long updateTime;
		
		/**
		 * Call the update function to process game logic.
		 * Then update ups to keep track of update cycles.
		 */
		private void requestUpdate(long delta)
		{
			update(delta);
			updateTime += delta;
			upsCounter++;
			if (updateTime > ticksPerSecond)
			{
				updateTime -= ticksPerSecond;
				ups = upsCounter;
				upsCounter = 0;
			}
		}

		private long frameDuration;
		private long frameTime;
		
		/**
		 * Call render after frameDuration time.  Throttle frames to 
		 * targetFPS.  Keep track of actual fps.
		 */
		private void requestRender(long delta)
		{
			frameTime += delta;
			if (frameTime > frameDuration)
			{
				frameTime -= frameDuration;
				fpsCounter++;

				render();
			}
			if (fpsTime > ticksPerSecond) 
			{
				fpsTime -= ticksPerSecond;
				fps = fpsCounter;
				fpsCounter = 0;
				Console.WriteLine();
				Console.WriteLine(DateTime.Now.TimeOfDay + " - F PS: " + fps + ", UPS: " + ups);
			}
		}

		/**
		 * The actual render code.
		 */
		private void render()
		{
			Console.Write(".");
			Thread.Sleep(new TimeSpan(10000L));
		}

		/** 
		 * The actual update code.  Sleep to simulate some work.
		 * Extra long updates drop the frame rate.
		 */
		private void update(long delta)
		{
			Thread.Sleep(new TimeSpan(1000L));
		}

		private void printRuler()
		{
			for (int i = 0; i < targetFPS; i++) 
			{
				if (i % 5 == 0)
					Console.Write("+");
				else
					Console.Write("-");
			}
			Console.WriteLine();
		}
	}
} 

Advertisement