C++ Logo

std-discussion

Advanced search

Re: is `\n` replacement of `std::endl`

From: Francis Grizzly Smit <grizzly_at_[hidden]>
Date: Fri, 26 Jul 2019 12:04:00 +1000
On 26/07/2019 11:57, praveer kumar via Std-Discussion wrote:
> HI Experts,
> Below is my sample code. I can see there is different time duration
> captured to process the same data by using "\n", '\n' and std::endl.


std::endl is basically equivalent to << '\n' << std::flush;


use std::endl when you want a newline followed by a flush of the buffer
(i.e. write the output straight out now)

and use '\n' when you want just to just put in a newline


> below is my sample code.
> I want to know is it OK to use '\n' all the time ?
>
> #include <fstream>
> #include <iostream>
>
> #include <chrono>
>
> // check performance among std::endl, "\n", '\n'
>
> template<typename T>
> auto _writeDataIntoFile( std::ofstream& of, const T& _data) {
> auto startTime = std::chrono::steady_clock::now();
> for (size_t i = 0; i < 1000; i++)
> {
> //of << _data << "\n";
> //of << _data << '\n';
> of << _data << std::endl;
> }
> auto endTime = std::chrono::steady_clock::now();
> auto timeElapsed = endTime - startTime;
> return timeElapsed.count();
> }
>
> int main()
> {
> std::ofstream outputFile("temp.txt", std::ios_base::trunc );
> auto duration = _writeDataIntoFile(outputFile, "String to be printed");
> std::cout << " Time taken = " << duration;
>
> return 0;
> }
>
-- 
    .~.     In my life God comes first....
    /V\         but Linux is pretty high after that :-D
   /( )\    Francis (Grizzly) Smit
   ^^-^^    http://www.smit.id.au/

Received on 2019-07-25 21:06:03