Is there a faster way to upload a file in C ++ using the command line?

I want to load a million random numbers from .txt into a vector using the command line:

program.exe < million-integers.txt

My code below works, but it takes a few seconds to run. Is there something I can do to make it faster? I found some solutions on SO, but they all seem to rely on hard-coding file paths. I want to be able to pass the file name through the command line.

vector<int> data;
int input;

while (cin >> input)
{
    data.push_back(input);
}
cout << "Data loaded." << endl;

(C ++ noob using Visual Studio on Win 8.1)

Change . In this case, I know that some improvements can be made, since I have another .exe that can do this in a second.

Edit : all integers are on the same line.

+4
5

: 4.08 . ? !

?

. : OS X 10.8, Clang, , , . ( ):

Running Time    Self        Symbol Name
3389.0ms   79.3%    76.0             std::__1::num_get<char, std::__1::istreambuf_iterator<char, std::__1::char_traits<char> > >::do_get(std::__1::istreambuf_iterator<char, std::__1::char_traits<char> >, std::__1::istreambuf_iterator<char, std::__1::char_traits<char> >, std::__1::ios_base&, unsigned int&, long&) const
824.0ms   19.2% 8.0          std::__1::basic_istream<char, std::__1::char_traits<char> >::sentry::sentry(std::__1::basic_istream<char, std::__1::char_traits<char> >&, bool)

, 98,5% . ! , ?

  • flockfile()
  • funlockfile()
  • pthread_mutex_unlock()

, std::cin C <stdio.h>, , . .

  • , <stdio.h>, .

  • , stdin, , , . . ... - 10 ? .

: , OS X, Windows. flockfile() pthread_mutex_unlock() , Windows.

№ 1

. ifstream, , . 0,42 - 10.

№2

, . .

№ 3

std::cin. , , . , .

, ifstream . , , 2 3 , .

+7

, .

  • std::vector<T>::reserve,
  • std::iostream::read 4K ( ) .

iostream , , , , , .

+5

...

, ( : https://gist.github.com/spundun/c91c07d7b8233e675d2e), 10 . MacBook Pro (, 2012 )

cpp $ruby gen_data.rb > data.txt 
cpp $c++ -O3 test1.cpp 
cpp $time ./a.out < data.txt 
Data loaded.

real    0m3.048s
user    0m3.023s
sys 0m0.011s
cpp $c++ -O3 test2.cpp 
cpp $time ./a.out data.txt 
data.txtData loaded.

real    0m0.351s
user    0m0.334s
sys 0m0.010s

ifstream cin. (vargs) , cin.

int main(int argc, char *argv[]){
  vector<int> data;
  int input;
  ifstream in;
  in.open(argv[1]);

  while (in >> input)
  {
        data.push_back(input);
  }
  cout << "Data loaded." << endl;
}

, ...

@DietrichEpp , 10 . cin, , .

+1

, , ios_base::sync_with_stdio, true. std::cin , C ++. . .

+1

. , , . , , ( , ).


, , , - .

, .

, () . , , .

:

  const unsigned int BUFFER_SIZE = 1024 * 1024;
  char buffer[BUFFER_SIZE];
  cin.read(buffer, BUFFER_SIZE);

std:: istringstream
std:: istringstream, . , "" , cin .


, , . . , .

"++ cin rdbuf setbuf" cin .

0
source

Source: https://habr.com/ru/post/1542683/


All Articles