Mas*_*gio 7 c++ terminal performance cmd
我注意到 Window 的命令提示符上的输出比在 Bash 上输出慢得多。我说的是命令提示符打印 40000 行大约需要 10 秒,而 Bash 需要不到十分之一秒。例如,以下代码用 1 到 40000 的整数填充堆栈,然后将其打印到标准输出和文本文件:
#include <iostream>
#include <chrono>
#include <fstream>
template <typename T>
struct Node {
Node(T data, Node *next = nullptr) {
this->data = data;
this->next = next;
}
T get_data() { return data; }
Node * get_next() { return next; }
void set_data(T data) { this->data = data; }
void set_next(Node *next) { this->next = next; }
private:
T data;
Node *next;
};
template <typename T>
class Stack {
public:
Stack() { head = nullptr; }
void push(T val) { head = new Node<T>(val, head); }
void print(std::ostream &os = std::cout) {
Node<T> *it = head;
while (it) {
os << it->get_data() << "\n";
it = it->get_next();
}
}
private:
Node<T> *head;
};
int main() {
Stack<int> s;
std::chrono::high_resolution_clock::time_point starttime = std::chrono::high_resolution_clock::now();
for (int i = 0; i < 40000; i++) {
s.push(i + 1);
}
s.print();
std::chrono::high_resolution_clock::time_point endtime = std::chrono::high_resolution_clock::now();
std::cout << "Time taken to print to stdout: " << std::chrono::duration_cast<std::chrono::duration<double>>(endtime - starttime).count() << " seconds.\n";
std::cout << "Writing to file...";
starttime = std::chrono::high_resolution_clock::now();
std::ofstream ofs("output.txt");
s.print(ofs);
endtime = std::chrono::high_resolution_clock::now();
std::cout << " Done\nTime taken to print to file output.txt: " << std::chrono::duration_cast<std::chrono::duration<double>>(endtime - starttime).count() << " seconds.\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在 Windows 上,打印到标准输出需要 6 到 10 秒,而写入文件需要大约 2 毫秒。在 Linux 上,打印到终端需要十分之一秒,而打印到文件的时间与 Windows 差不多。有没有办法提高CMD的输出速度?