LoginSignup
0
1

More than 3 years have passed since last update.

SwiftでFPSカウンターを作る

Last updated at Posted at 2020-11-11

ソースコード

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())
    }
}

使い方

ViewController.swift

final class ViewController: UIViewController {

    private var fpsCounter = FPSCounter()

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

    private func hoge() {
        // なんらかの処理

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

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1