Make an FPS counter in Swift

Source code

FPSCounter.swift


import Foundation

class FPSCounter {
    private var baseTime: Int!
    private var count: Int = 0
    private var fps: Float = 0

    func getFPS() -> Float {
        return fps
    }

    func tickStart() {
        baseTime = timeSince1970Millis()
    }

    func tick() {
        count = count + 1;
        let now = timeSince1970Millis()
        if (now - baseTime >= 1000) {
            fps = Float(count * 1000) / Float(now - baseTime)
            baseTime = now
            count = 0
        }
    }

    private func timeSince1970Millis() -> Int {
        return Int((Date().timeIntervalSince1970 * 1000.0).rounded())
    }
}

How to use

ViewController.swift



final class ViewController: UIViewController {

    private var fpsCounter = FPSCounter()

    override func viewDidLoad() {
        super.viewDidLoad()
        fpsCounter.tickStart()
    }

    private func hoge() {
        //Some processing

        fpsCounter.tick()
        print("fps: \(fpsCounter.getFPS())")
    }
}

Recommended Posts

Make an FPS counter in Swift
Create an HTML/XML generator in Swift (dynamicMemberLookup)
Find an approximation of cosx in Swift
How to make an image partially transparent in Processing
Compare objects in Swift
Make Blackjack in Java
Try to make an addition program in several languages
Division becomes 0 in Swift
Multidimensional array in Swift
I tried to make an application in 3 months from inexperienced
[swift5] Try to make an API client with various methods
Make an instagram clone app ④
Refactoring: Make Blackjack in Java
Make an instagram clone app ②
Photo library in Swift UI
Make an android app. (Day 5)
Implement Swift UITextField in code
Make an instagram clone app ③
Make an instagram clone app ①
Make html available in Vapor
Swift: A trap when setting multiple initial elements in an array