Advertisement
luluco250

C++ Win32 Delta Time

Dec 30th, 2016
318
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <Windows.h>
  2. #include <iostream>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. //internal variables
  8. long double lastMilliseconds = 0.0;
  9. long double deltatime = 0.0;
  10. unsigned int limit = 0;
  11.  
  12. //function prototypes
  13. void SetDeltaTime();
  14. unsigned int FPSLimit(int targetFPS);
  15. DWORD CALLBACK Display(LPVOID parameter);
  16. DWORD CALLBACK CalcDelta(LPVOID parameter);
  17. DWORD CALLBACK MessageProc(LPVOID parameter);
  18.  
  19. BOOL main(int argc, char* argv[]) {
  20.     int fps = 0;
  21.     if (argc > 1) { //if a number is passed, set the FPS limit to it
  22.         fps = strtol(argv[1], 0, 0);
  23.     }
  24.     limit = FPSLimit(fps);
  25.  
  26.     CreateThread(0, 0, CalcDelta, 0, 0, 0); //create thread to calculate the delta time
  27.     CreateThread(0, 0, Display, 0, 0, 0); //create thread to display the FPS
  28.  
  29.     MSG msg; //hold windows messages here
  30.     while (msg.message != WM_QUIT) {
  31.         while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) {
  32.             TranslateMessage(&msg);
  33.             DispatchMessage(&msg);
  34.         }
  35.     }
  36.     return FALSE;
  37. }
  38.  
  39. void SetDeltaTime() {
  40.     SYSTEMTIME time;
  41.     GetSystemTime(&time);
  42.     long double milliseconds = (time.wSecond * 1000.0) + time.wMilliseconds;
  43.     deltatime = (milliseconds - lastMilliseconds) * 0.001;
  44.     lastMilliseconds = milliseconds;
  45. }
  46.  
  47. unsigned int FPSLimit(int targetFPS) {
  48.     return (unsigned int)(1.0 / (long double)targetFPS * 1000.0);
  49. }
  50.  
  51. DWORD CALLBACK Display(LPVOID parameter) {
  52.     while (true) {
  53.         Sleep(1000);
  54.         //unsigned long long was required because otherwise it just displayed infinite with the FPS uncapped
  55.         cout << (unsigned long long int)(1.0 / deltatime) << endl;
  56.     }
  57.     return 1;
  58. }
  59.  
  60. DWORD CALLBACK CalcDelta(LPVOID parameter) {
  61.     while (true) {
  62.         Sleep(limit);
  63.         SetDeltaTime();
  64.     }
  65.     return 1;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement