Advertisement
drankinatty

C++ timed read of lines from file into dynamic list<string>

Oct 8th, 2017
318
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. /* C++ best of 10 reads (7200 rpm laptop drive):
  2.  * read/stored 25481 lines in 0.00813842 sec.
  3.  * total heap usage: 76,465 allocs, 76,464 frees, 2,151,883 bytes allocated
  4.  * (reading, e.g. /usr/share/dict/words)
  5.  */
  6. #include <iostream>
  7. #include <iomanip>
  8. #include <fstream>
  9. #include <string>
  10. #include <list>
  11. #include <time.h>
  12.  
  13. using namespace std;
  14.  
  15. /** return the number of seconds (nanosecond resolution)
  16.  *  using clock_gettime/CLOCK_REALTIME
  17.  */
  18. double clkrtv (void)
  19. {
  20.     struct timespec ts;
  21.     double sec;
  22.  
  23.     clock_gettime (CLOCK_REALTIME, &ts);
  24.     sec = ts.tv_nsec;
  25.     sec /= 1e9;
  26.     sec += ts.tv_sec;
  27.  
  28.     return sec;
  29. }
  30.  
  31. /* output lines read/stored and time taken */
  32. void printlist (list<string> *l, double tm) {
  33.    
  34.     cout << "read/stored " << l->size() << " lines in "
  35.         << tm << " sec." << endl;
  36. }
  37.  
  38.  
  39. int main (int argc, char **argv) {
  40.    
  41.     double t1, t2;
  42.     string line;
  43.     list<string> buf;   // doublely-linked list of string
  44.  
  45.     if (argc != 2) {
  46.         cerr << "One argument is required." << endl;
  47.         return 1;
  48.     }
  49.    
  50.     ifstream f (argv[1]);       // open file
  51.    
  52.     t1 = clkrtv();
  53.     while (getline (f, line)) { // read lines into buf
  54.         buf.push_back(line);
  55.     }
  56.     t2 = clkrtv();
  57.    
  58.     f.close();
  59.    
  60.     printlist (&buf, t2-t1);
  61.    
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement