Nyhetsgrupper: comp.lang.c++
Från: fifoforlifo <fifoforl...@gmail.com>
Datum: Fri, 12 Jun 2009 00:22:56 -0700 (PDT)
Lokalt: Fre 12 Juni 2009 09:22
Ämne: Re: C++ programming challenge
I thought this competition sounded fun, so I gave it a shot. The
following is a 2-threaded program that overlaps reads and computation. I had to use boost::thread for this, but this should all be doable in C++0x -- but I'll let you be the final judge of whether it's an acceptable entry. As many pointed out, the problem is I/O bound, so that's what I tackled first. The computation part is nearly identical to Chris' code, I could not beat the simple accumulate-into-256-wide-table. So cheers for finding the best solution there :-) FYI timings on my machine were: Read the entire 280MB file, do no processing : 0.25 seconds Chris' program : 0.6 seconds This program : 0.4 seconds /// This program counts plain ol' alphabet characters' frequency in a /* }; #else #include <sys/time.h> class CStopWatch { private: typedef struct { timeval start; timeval stop; } stopWatch; stopWatch timer; public: void startTimer( ) { gettimeofday(&(timer.start),0); } void stopTimer( ) { gettimeofday(&(timer.stop),0); } double getElapsedTime() { timeval res; timersub(&(timer.stop),&(timer.start),&res); return res.tv_sec + res.tv_usec/1000000.0; } }; #endif #include <stdio.h> #define BLOCK_SIZE 0x10000u static unsigned char inbuf[INBUF_SIZE]; static boost::mutex ioMutex; static int totals[256] = {0}; struct Reader { Reader(const char* pFileName_) : pFileName(pFileName_) {} void operator()() { while (!feof(pFile) && !ferror(pFile)) { const size_t nextWriteCursor = (writeCursor + 1) % { fclose(pFile); }; static void AccumulateTotals(const unsigned char* pBuffer, size_t size) { const unsigned char* pc = pBuffer; const unsigned char* const pcEnd = pc + size; for (; pc != pcEnd; ++pc) { const unsigned char c = *pc; ++totals[c]; } } int main(int argc, char** argv) { if (argc < 2) { printf("\nusage:\n\t%s <text_file_name>\n", argv[0]); return -1; } // launch a reader thread // accumulate totals from buffers as they are AccumulateTotals(&inbuf[BLOCK_SIZE * readCursor], inbufAmt long totalAlphaChars = 0; for (size_t u = 0; u < 26; ++u) { stopWatch.stopTimer(); const double elapsed = stopWatch.getElapsedTime(); return 0; }
Du måste Logga in innan du kan skicka meddelanden.
Om du vill skicka ett meddelande måste du först delta i den här gruppen.
Uppdatera ditt smeknamn på sidan Prenumerationsinställningar innan du skickar.
Du har inte behörighet att skicka meddelanden.
| ||||||||||||||