Advertisement
Terrah

ups

Feb 6th, 2019
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.49 KB | None | 0 0
  1. local _exit=Exit;Exit=function(ret)print(ret); GetKey(); return ret+1; end
  2.  
  3. local UPS = {Target=50, Avg={}, AvgIndex=1, MaxAvg=100, FramesCnt=0, Last=os.clock(), LastFPS=0, SleepK=0, LastFrame=os.clock()};
  4.  
  5. function UPS:GetFPS()
  6.    
  7.     local now = os.clock();
  8.    
  9.     if now - self.Last > 1 then
  10.        
  11.         self.LastFPS = ((self.FramesCnt / (now - self.Last)) + 1);
  12.         self.FramesCnt = 0;
  13.        
  14.         if #self.Avg < self.MaxAvg then
  15.             table.insert(self.Avg, self.LastFPS);
  16.         else
  17.             self.Avg[self.AvgIndex] = self.LastFPS;
  18.            
  19.             if self.AvgIndex >= self.MaxAvg then
  20.                 self.AvgIndex = 1;
  21.             else
  22.                 self.AvgIndex = self.AvgIndex + 1;
  23.             end
  24.         end
  25.        
  26.         self.Last = now;
  27.     end
  28.    
  29.     if #self.Avg <= 0 then
  30.         return 0, 0;
  31.     end
  32.    
  33.     local sum=0;
  34.  
  35.     for n=1, #self.Avg do
  36.         sum = sum + self.Avg[n];
  37.     end
  38.  
  39.     return math.floor(sum / #self.Avg), self.LastFPS;
  40. end
  41.  
  42. function UPS:Sleep()
  43.  
  44.     self.FramesCnt = self.FramesCnt + 1;
  45.  
  46.     local fps, last = self:GetFPS(true);
  47.    
  48.     if fps > self.Target and last > 1 then
  49.    
  50.         local n = 100;
  51.         while n > 0 do
  52.        
  53.             if last > self.Target *  (n/100) then
  54.                 self.SleepK=math.floor((1000/self.Target) * (n/100));
  55.                 break;
  56.             end
  57.        
  58.             n = n - 1;
  59.         end
  60.  
  61.         Sleep(self.SleepK);
  62.     end
  63.    
  64.     self.LastFrame=os.clock();
  65. end
  66.  
  67. local test = Timer.New();
  68. test:Start();
  69.  
  70. while true do
  71.     UPS:Sleep();
  72.    
  73.     if test:Elapsed() > 1000 then
  74.         print(UPS.SleepK, UPS:GetFPS());
  75.         test:Reset();
  76.         test:Start();
  77.     end
  78.  
  79.     for n=1, 100000 do
  80.         math.random();
  81.     end
  82. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement