Simple Logger ใน C ++

Oct 21 2020

ฉันกำลังทำเกมโดยใช้ภาษา C ++ ในที่สุดฉันก็ต้องการคนตัดไม้ แต่ฉันไม่พอใจกับวิธีแก้ปัญหาใด ๆ ที่มีอยู่ หลังจากนั้นไม่นานฉันก็เขียนส่วนหัวของตัวเองชื่อlog.h :


#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
#include <fstream>
#include <sstream>

class Logger {
    private:
        std::string logFileName = "log.txt";
        bool print = true;
        bool save = true;
        
        void log(std::string s, std::string i) {
            time_t cuT;
            struct tm *loT;
            time(&cuT);
            loT = localtime(&cuT);
            
            std::stringstream ss;
            ss << std::setw(2) << std::setfill('0') << loT->tm_hour << ':';
            ss << std::setw(2) << std::setfill('0') << loT->tm_min << ':';
            ss << std::setw(2) << std::setfill('0') << loT->tm_sec;
            ss << i << s << "\n";
            
            if(save) {
                std::ofstream of;
                of.open(logFileName, std::ios_base::app | std::ios::out);
                of << ss.rdbuf();
            }
            if(print) {
                std::cout << ss.str();
            }
        }
    public:
        void configure(std::string logFileName_, bool print_, bool save_) {
            this->print = print_;
            this->save = save_;
            this->logFileName = logFileName_;
        }
        
        void note(std::string s) {
            log(s, " NOTE: ");
        }
        
        void error(std::string s) {
            log(s, " ERROR: ");
        }
        
        void warn(std::string s) {
            log(s, " WARNING: ");
        }
};

ห้องสมุดของฉันสามารถพิมพ์เวลาปัจจุบันตลอดจนข้อมูลอื่น ๆ ไปยังคอนโซลและบันทึกข้อมูลนี้ลงในไฟล์ แต่ฉันได้ทำการเปรียบเทียบสองสามข้อและปรากฎว่าโปรแกรมบันทึกข้อมูลของฉันช้ากว่ามากเมื่อเทียบกับstd :: coutปกติ

เนื่องจากความเร็วเป็นสิ่งสำคัญสำหรับเกมฉันจึงอยากถามว่ามีวิธีใดบ้างในการเพิ่มประสิทธิภาพโปรแกรมของฉันหรือหากจำเป็นเพื่อปรับปรุง

คำตอบ

3 mkamerath Oct 21 2020 at 04:49

บางสิ่งที่ควรทราบ

  1. เมื่อเวลาทำสิ่งที่เกี่ยวข้องใน C ++ ใช้งานไม่ได้std::chronoclock()
  2. บันทึกของคุณจะไม่ทำงานหากใช้ในหลายไฟล์ แทนที่จะอยู่ในไฟล์. h ให้ใส่คำจำกัดความของคนตัดไม้ในไฟล์ cpp และสร้างทั้งสองอย่างเข้าด้วยกัน
  3. ใช้รวมยามสำหรับไฟล์ส่วนหัว
    #ifndef LOG_H
    #define LOG_H

    // Code

    #endif
  1. กำหนดคอนสตรัคเตอร์และใช้อย่างถูกต้องและกำจัดการกำหนดค่า
    Log(std::string fileName, bool printToConsole, bool saveToFile) :
        logFileName(fileName),
        print(printToConsole),
        save(saveToFile)
    {
    }
  1. อย่าใช้เครื่องหมายขีดล่างในการตั้งชื่อสิ่งต่างๆ กฎทั่วไปสำหรับ c ++ คือชื่อคลาสคือ PascalCase และฟังก์ชันคือ camelCase
  2. std :: cout ทำงานช้าลองใช้ sprintf เพื่อให้เร็วขึ้น
  3. อย่าเขียนลงไฟล์ทุกครั้งที่โทรเข้าสู่ระบบ การเปิดไฟล์และการเขียนไฟล์ทำได้ช้า ลองเขียนลงในไฟล์ด้วยการประทับเวลาหรือรวบรวมบันทึกสองสามบันทึกก่อนที่จะเขียน