simTime aus realer Zeit ableiten



  • Für eine Simulation benötige ich eine Singleton Objekt, das die Sim-Time verwaltet. Ist dieser Entwurf so sinnvoll?

    #include <iostream>
    #include <chrono>
    
    class simTime
    {
    private:
      simTime(){}
      simTime( const simTime & );
      simTime& operator=( simTime );
      ~simTime(){}
    
      double factor_;
      size_t timeSec_;
    
    public:
      static simTime& Instance()
      {
        static simTime instance;
        return instance;
      }
    
      double getFactor() {return factor_;}
      void setFactor(double factor){factor_ = factor;}
    
      size_t getTimeSec() {return timeSec_;}
      void setTimeSec(size_t timeSec){timeSec_ = timeSec;}
      void resetTime(){timeSec_ = 0;};
    };
    
    simTime& sT = simTime::Instance();
    
    int main()
    {
        sT.setFactor(10);
        sT.setTimeSec(0);
    
        std::chrono::time_point<std::chrono::system_clock> start, realTime;
        start = std::chrono::system_clock::now();
    
        std::chrono::duration<int> elapsed_seconds;
    
        while (true)
        {
            realTime = std::chrono::system_clock::now();
            std::chrono::duration<float> elapsed_seconds;
            static std::chrono::duration<float> old_elapsed_seconds(0);
    
            elapsed_seconds = realTime-start;
            std::time_t realTimeDuration = std::chrono::system_clock::to_time_t(realTime);
    
            if (elapsed_seconds.count() >= (old_elapsed_seconds.count() + 1/sT.getFactor()))
            {
                sT.setTimeSec(elapsed_seconds.count() * sT.getFactor());
    
                std::cout << "elapsed time: " << elapsed_seconds.count() << "s  simTime: " << sT.getTimeSec() << "s\n";
                old_elapsed_seconds = elapsed_seconds;
            }
    
            if (elapsed_seconds.count() > 15)
            {
                break;
            }
        }
    
        return 0;
    }
    


  • Warum brauchst du ein Singleton?


Log in to reply