高 cpu 负载。 C++/sfml

High cpu loading. C++/sfml

我的程序加载处理器 80%。前段时间我在 gpu 上遇到了同样的问题,我通过计时器解决了它。 Cpu 负载大约为 50-60 %,现在为 80 %。我做错了什么?我无法解决它的问题。

#include <fstream>
#include <SFML/Graphics.hpp>
#include <ctime>
using namespace std;
char * readFile(char * filePath, unsigned int &lengthBuffer, fstream &f) {
    f.open(filePath, ios::in | ios::app | ios::binary);
    f.seekg (0, f.end);
    lengthBuffer = f.tellg();
    f.seekg (0, f.beg);
    char * fileBuffer = new char[lengthBuffer];
    f.read(fileBuffer, lengthBuffer);
    f.close();
    return fileBuffer;
}
char * writeFile(char * fileBuffer, char * filePath, unsigned int &lengthBuffer, fstream &f, bool &fileCreated){
    filePath[23] += 1;
    f.open(filePath, ios::out | ios::app | ios::binary);
    f.write(fileBuffer, lengthBuffer);
    filePath[23] -= 1;
    fileCreated = 1;
    f.close();
    return fileBuffer;
}

void removeFile(char * filePath, bool &fileCreated) {
    filePath[23] += 1;
    remove(filePath);
    filePath[23] -= 1;
    fileCreated = 0;
}
unsigned int mouse(unsigned int &funcSelector, bool &mouseLeft, sf::RenderWindow &window) {
    mouseLeft = sf::Mouse::isButtonPressed(sf::Mouse::Left);
    sf::Vector2i mouse = sf::Mouse::getPosition(window);
    if (mouseLeft & mouse.y < 100) {
        funcSelector = 1 + mouse.x/100;
    }
    return funcSelector;
}
int main(){
    sf::RenderWindow window(sf::VideoMode(500, 400), "COT++", sf::Style::Titlebar);
    sf::VertexArray points(sf::Points, 3000);
    sf::Event event;
    fstream f;
    bool mouseLeft, fileCreated = 0;
    unsigned int n = 0, funcSelector = 0, lengthBuffer = 0;
    float start = 0, now = 0, x = 0.f, y = 1.f, pos = 0.f;
    char * fileBuffer, filePath[30] = "c:/users/79994/desktop/a.exe";
    while (x < 500.f){
        points[n].position = sf::Vector2f(x + pos, y + pos);
        points[n].color = sf::Color::Green;
        x += 1.f;
        n += 1;
        if (x == 500.f & y < 100.f){
            x = 0.f;
            y += 100.f;
        }
    }
    x = 100.f, y = 1.f;
    while (x < 600.f){
        points[n].position = sf::Vector2f(x + pos, y + pos);
        points[n].color = sf::Color::Green;
        y += 1.f;
        n += 1;
        if (y > 101.f){
            x += 100.f;
            y = 1.f;
        }
    }
    while (window.isOpen())
    {
        while (window.pollEvent(event)) {
            if((clock()-start) > 50){
            start = clock();
            switch(funcSelector){
                case 5: window.close();
                break;
                case 1: if (lengthBuffer == 0){
                    fileBuffer = readFile(filePath, lengthBuffer, f);
                }    
                break;
                case 2: if (lengthBuffer > 0 & fileCreated == 0) {
                    writeFile(fileBuffer, filePath, lengthBuffer, f, fileCreated);
                }
                break;
                case 3: removeFile(filePath, fileCreated);  
                break;
            }
            mouse(funcSelector, mouseLeft, window);
            window.clear();
            window.draw(points);
            window.display();
        }
    }
    }
    return 0;
}

P.S。 "It looks like your post is mostly code; please add some more details" - 我想我描述的足够详细了。

这取决于你想做什么。对于您给出的简单示例,您可以使用 waitEvent 而不是 pollEvent。我建议检查 waitEvent 是否适合您的需求,但看起来会。

但是,如果您坚持使用 pollEvent,请继续阅读!

您的 while(window.pollEvent(event)) 循环在 100% 的时间内全速 运行,不停地轮询,尽管看起来您的目标是仅 "do work" 每个 50 时钟。 (除了 CLOCKS_PER_SECwhich is implementation defined... and std::clock may not correlate to wall time... and CLOCKS_PER_SEC might be hardcoded to 1 million when that isn't a meaningful value 之外,时钟并不始终与实际测量单位相关...但我离题了。无论您如何跟踪时间,您的问题都会存在,但是对于您编写的代码您可能需要一些其他计时机制。)

这是一个可能的解决方案,只需对您的代码进行最少的更改。替换:

    while (window.pollEvent(event)) {
        if((clock()-start) > 50){

具有以下内容:

    while (window.pollEvent(event)) {
        const auto delta = clock() - start;
        if (delta < 50) {
          std::this_thread::sleep_for(std::chrono::microseconds(
            static_cast<int>(1E6 * (50 - delta) / CLOCKS_PER_SEC)));
        } else {

它的作用不是不断地调用 window.pollEvent(event),而是会调用它,如果需要的话可以睡一会儿,然后做一些工作。

这种方法也有一些缺点,但它应该可以帮助您开始思考问题。

您还需要 #include <chrono>(或者,如果您不使用 C++11 或更晚的时间,您可以找到一些其他的睡眠方式来达到几乎正确的持续时间)。

仅仅通过查看您的代码来尝试和猜测或多或少是困难且不精确的。 您应该尝试使用分析器分析您的代码。

PS:您在 "readFile" 和 "writeFile" 中似乎也有内存泄漏,您分配了一个缓冲区但再也没有释放它。

char * readFile(char * filePath, unsigned int &lengthBuffer, fstream &f) {
    // [...]
    char * fileBuffer = new char[lengthBuffer];
    // here you allocated memory on the heap, but you'll never free it.
    // [...]
    return fileBuffer;
}

我还认为根本不使用那些动态字符数组和 C 文件。只需使用 std::string 和 std::ostream。 ostream 适用于更多的 STL 和字符串,您不必关心它的内存使用和潜在的内存泄漏。它会自行清理而不是字符数组。