Skip to content

Commit

Permalink
cpp: add time duration for std::endl and \n in standard output (#59)
Browse files Browse the repository at this point in the history
  • Loading branch information
Oreoxmt authored Jan 11, 2024
1 parent aebc706 commit b998732
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions website/docs/cpp/cpp-wiki.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ int main() {

`std::endl` inserts a newline character (`\n`) into the output stream and flushes the buffer.

### What does `std::endl` do?

The following code examples show the difference between using `std::endl` and not using it.

<Tabs>
Expand Down Expand Up @@ -86,6 +88,8 @@ The following code examples show the difference between using `std::endl` and no

</Tabs>

### Standard output vs file output

In standard output, `\n` usually has the same effect as `std::endl`, that is, it inserts a newline character and flushes the buffer. However, in file output, `\n` does not flush the stream, while `std::endl` does.

:::info quote
Expand Down Expand Up @@ -187,3 +191,56 @@ To see the difference between `std::endl` and `\n` in file output, run the follo

</TabItem>
</Tabs>

### Performance

The following example shows the duration for printing 100,000 numbers with `std::endl` and `\n` in standard output.

<Tabs>
<TabItem label="Code" value="code">

```cpp
#include <iostream> // for cin, cout
#include <chrono> // for timers

int endl_each_time(int n = 10000) {
const auto start_time = std::chrono::high_resolution_clock::now();
for (int i = 0; i < n; i++) {
std::cout << i << std::endl;
}
const auto end_time = std::chrono::high_resolution_clock::now();
auto duration_ns = std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time);
return duration_ns.count();
}

int new_line_each_time(int n = 10000) {
const auto start_time = std::chrono::high_resolution_clock::now();
for (int i = 0; i < n; i++) {
std::cout << i << "\n";
}
const auto end_time = std::chrono::high_resolution_clock::now();
const auto duration_ns = std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time);
return duration_ns.count();
}

int main() {
int endl_duration = endl_each_time();
int new_line_duration = new_line_each_time();
std::cout << "endl_each_time duration: " << endl_duration << "ns" << std::endl;
std::cout << "new_line_each_time duration: " << new_line_duration << "ns" << std::endl;
return 0;
}
```
</TabItem>
<TabItem label="Output" value="output">
```shell
...
9999
endl_each_time duration: 9717ns
new_line_each_time duration: 8896ns
```

</TabItem>
</Tabs>

0 comments on commit b998732

Please sign in to comment.