【问题标题】:Why is console animation so slow on Windows? (And is there a way to improve speed?)为什么控制台动画在 Windows 上这么慢? (有没有办法提高速度?)
【发布时间】:2012-12-27 01:30:15
【问题描述】:

好吧,我很无聊,所以想在控制台窗口中制作动画。

现在,当我设置第一个位时,我注意到它非常慢,整个屏幕填充字符大约需要 333 毫秒..

我想知道是否有办法至少获得 ~20 fps?

这是我的代码:

#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <iostream>
#include <array>

#define WIDTH (100)
#define HEIGHT (35)

bool SetWindow(int Width, int Height) { 
    _COORD coord; 
    coord.X = Width; coord.Y = Height; 

    _SMALL_RECT Rect; 
    Rect.Left = 0;              Rect.Top = 0;  
    Rect.Bottom = Height - 1;   Rect.Right = Width - 1; 

    HANDLE Handle = GetStdHandle(STD_OUTPUT_HANDLE); 
    if (Handle == NULL)return FALSE; 
    SetConsoleScreenBufferSize(Handle, coord);
    if(!SetConsoleWindowInfo(Handle, TRUE, &Rect)) return FALSE; 
    return TRUE; 
} 

std::array<std::array<unsigned char, WIDTH+1>, HEIGHT> Screen;//WIDTH+1 = prevent cout from undefined behaviour

void Putchars(unsigned char x){
    for(int row = 0; row < HEIGHT; ++row){
        std::fill(Screen[row].begin(),Screen[row].end(),x);
        Screen[row].at(WIDTH) = 0;//here = prevent cout from undefined behaviour
    }
}

void ShowFrame(DWORD delay = 0,bool fPutchars = false, unsigned char x = 0){
    if(fPutchars)Putchars(x);
    if(delay)Sleep(delay);
    system("CLS");
    for(int row = 0; row < HEIGHT; ++row)
        std::cout << Screen[row].data() << std::flush;
}

int _tmain(int argc, _TCHAR* argv[]){//sould execute @~63 fps, yet it executes @~3-4 fps
    if(SetWindow(100,HEIGHT)){
        for(unsigned char i = 219; i != 0; --i)
        ShowFrame(16,true, i);
    }
    return 0;
}

编辑:在阅读了无数答案、提示和 cmets 之后,我终于解决了,谢谢你们,这是我最终的“基础”代码:

#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <iostream>
#include <array>

#define WIDTH (100)
#define HEIGHT (34)

HANDLE current;
HANDLE buffer;

bool SetWindow(int Width, int Height) { 
    _COORD coord; 
    coord.X = Width; coord.Y = Height; 

    _SMALL_RECT Rect; 
    Rect.Left = 0;              Rect.Top = 0;  
    Rect.Bottom = Height - 1;   Rect.Right = Width - 1; 

    HANDLE Handle = GetStdHandle(STD_OUTPUT_HANDLE); 
    if (Handle == NULL)return FALSE; 
    SetConsoleScreenBufferSize(Handle, coord);
    if(!SetConsoleWindowInfo(Handle, TRUE, &Rect)) return FALSE; 
    return TRUE; 
} 

std::array<std::array<CHAR, WIDTH+1>, HEIGHT> Screen;//WIDTH+1 = prevent cout from undefined behaviour

void Putchars(CHAR x){
    for(int row = 0; row < HEIGHT; ++row){
        std::fill(Screen[row].begin(),Screen[row].end(),x);
        Screen[row].at(WIDTH) = 0;//here = prevent cout from undefined behaviour
    }
}

void ShowFrame(DWORD delay = 0, bool fPutchars = false, CHAR x = 0){
    if(fPutchars)Putchars(x);
    if(delay)Sleep(delay);
    //system("CLS");
    _COORD coord;
    coord.X = 0;
    for(int row = 0; row < HEIGHT; ++row)
    {
        coord.Y = row;
        FillConsoleOutputCharacterA(buffer,Screen[row].data()[0],100,coord,NULL);
    }
}

int _tmain(int argc, _TCHAR* argv[]){//sould execute @~63 fps, yet it executes @~3-4 fps
    SetWindow(WIDTH, HEIGHT);
    current = GetStdHandle (STD_OUTPUT_HANDLE);
    buffer = CreateConsoleScreenBuffer (
        GENERIC_WRITE,
        0,
        NULL,
        CONSOLE_TEXTMODE_BUFFER,
        NULL
    );
    SetConsoleActiveScreenBuffer (buffer);

    if(SetWindow(WIDTH,HEIGHT)){
        for(CHAR i = 219; i != 0; --i)
        ShowFrame(250,true, i);
    }
    CloseHandle (buffer); //clean up
    return 0;
}

而且它似乎工作得非常快:)

【问题讨论】:

  • Windows 控制台 is 与例如油灰。类似问题:stackoverflow.com/questions/7404551/…。 (不是重复的 - 它询问为什么而不是如何修复它
  • 使用控制台功能(我想我之前说过,所以你没做过?)
  • 这么多的同步......那么禁用同步呢?
  • @Cheersandhth.-Alf 哪个功能? :o 什么控制台功能? xD
  • 你现在,谷歌"console functions"。哦,我是为你做的。但无论如何

标签: c++ windows winapi console console-application


【解决方案1】:

只要看一眼您的代码,您就会每帧生成一个单独的程序(“CLS”)。这本身就可怕慢了。

与某些 cmets 不同,Windows 控制台至少能够相当在几乎正确使用的情况下达到合理的速度(例如:您可以比任何显示器显示的速度更快地更新控制台数据)。

仅供参考,这里是为 Windows 控制台编写的 John Conway 的 Game of Life 版本。出于计时目的,它只是生成一个随机启动屏幕并运行 2000 代,然后停止。在我的机器上,它在大约 2 秒内完成 2000 代,或每秒大约 1000 帧(没用,因为典型的监视器只能在 60-120 Hz 左右更新)。在带有全屏控制台的 32 位 Windows 下,它大约可以翻倍(同样,至少在我的机器上)。我很确定只要做一点工作,这可能会加快一些速度,但我从来没有看到任何打扰的理由。

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <io.h>

#define     ROWS        50
#define     COLS        80

// The total number of generations is really double this number.
int generations = 1000;

int civ1[ROWS+2][COLS+2], civ2[ROWS+2][COLS+2];

CHAR_INFO disp[ROWS][COLS];
HANDLE console;
COORD size = { COLS, ROWS };
COORD src = { 0, 0};
SMALL_RECT  dest = { 0, 0, COLS, ROWS };

void ClrScrn(char attrib) {
    COORD pos = { 0, 0};
    DWORD written;
    unsigned size;

    size = ROWS * COLS;

    FillConsoleOutputCharacter(console, ' ', size, pos, &written);
    FillConsoleOutputAttribute(console, attrib, size, pos, &written);
    SetConsoleCursorPosition(console, pos);
}

void fill_edges(int civ1[ROWS+2][COLS+2]) {
    int i, j;

    for (i=1; i<=ROWS; ++i) {
        civ1[i][0] = civ1[i][COLS];
        civ1[i][COLS+1] = civ1[i][1];
    }
    for (j=1; j<=COLS; ++j) {
        civ1[0][j] = civ1[ROWS][j];
        civ1[ROWS+1][j] = civ1[1][j];
    }
    civ1[0][0] = civ1[ROWS][COLS];
    civ1[ROWS+1][COLS+1] = civ1[1][1];
    civ1[0][COLS+1] = civ1[ROWS][1];
    civ1[ROWS+1][0] = civ1[1][COLS];
}

void update_generation(int old_gen[ROWS+2][COLS+2], 
                       int new_gen[ROWS+2][COLS+2])
{
    int i, j, count;

    for (i = 1; i <= ROWS; ++i)
    {
        for (j = 1; j <= COLS; ++j)
        {
            count = old_gen[i - 1][j - 1] +
                old_gen[i - 1][j] +
                old_gen[i - 1][j + 1] +
                old_gen[i][j - 1] +
                old_gen[i][j + 1] +
                old_gen[i + 1][j - 1] +
                old_gen[i + 1][j] +
                old_gen[i + 1][j + 1];

            switch(count) 
            {
            case 2:
                new_gen[i][j] = old_gen[i][j];
                break;

            case 3:
                new_gen[i][j] = 1;
                disp[i-1][j-1].Char.AsciiChar = '*';
                break;
            default:
                new_gen[i][j] = 0;
                disp[i-1][j-1].Char.AsciiChar = ' ';
                break;
            }
        }
    }
    WriteConsoleOutput(console, (CHAR_INFO *)disp, size, src, &dest);
    fill_edges(new_gen);
}

void initialize(void)
{
    int i, j;

    ClrScrn(0x71);
    srand(((unsigned int)time(NULL))|1);

    for (i = 1; i <= ROWS; ++i)
    {
        for (j = 1; j <= COLS; ++j)
        {
            civ1[i][j] = (int)(((__int64)rand()*2)/RAND_MAX);
            disp[i-1][j-1].Char.AsciiChar = civ1[i][j] ? '*' : ' ';
            disp[i-1][j-1].Attributes = 0x71;
        }
    }
    WriteConsoleOutput(console, (CHAR_INFO *)disp, size, src, &dest);
    fill_edges(civ1);
}

int main(int argc, char **argv) {

    int i;

    if ( argc != 1)
        generations = atoi(argv[1]);

    console = GetStdHandle(STD_OUTPUT_HANDLE);
    initialize();
    for (i = 0; i <generations; ++i)
    {
        update_generation(civ1, civ2);
        update_generation(civ2, civ1);
    }
    return EXIT_SUCCESS;
}

如果没有别的,它有一个ClrScrn 函数,你可能会觉得很方便。

【讨论】:

  • 附带说明,如果输出属性更改频​​繁的数据,WriteConsoleOutput 可能会非常慢。使用常量属性绘制全屏字符,例如 0x0071 导致 >150fps。在属性是随机 0x0000-0x00FF 的情况下做同样的事情会使窗口以 5fps 的速度下降!!! (这里是Win7)
【解决方案2】:

不要使用 cout 写入控制台。请改用控制台 API 中的 WriteConsole。你可以像在普通图形动画中一样使用双缓冲,使用 SetConsoleActiveScreenBuffer。 http://msdn.microsoft.com/en-us/library/windows/desktop/ms682073.aspx

同样不要使用 system("cls") 来清屏,FillConsoleOutputCharacter 会快很多。

【讨论】:

  • +1 建议使用 SetConsoleActiveScreenBuffer 进行双缓冲。
  • 您可能希望在为 SetConsoleActiveScreenBuffer() 提供 +1 之前进行基准测试。这个(SLOW)功能对于保存/恢复屏幕内容确实更有意义。例如,一个文件查看程序可能会切换到一个干净的缓冲区,显示,然后恢复以前的。控制台速度的关键不是双缓冲,而是减少对控制台 I/O 函数的调用次数,因为每个调用都需要一个本地过程调用,这代表了控制台速度的最大份额。
猜你喜欢
  • 2011-09-29
  • 1970-01-01
  • 1970-01-01
  • 2011-11-16
  • 1970-01-01
  • 2011-07-13
  • 1970-01-01
  • 2013-11-28
  • 2011-05-02
相关资源
最近更新 更多