Professional Documents
Culture Documents
How To Measure The Time in Multi
How To Measure The Time in Multi
How To Measure The Time in Multi
After spending about an hour trying to figure out what was the problem that my threaded version of a program took more time than the single-core one, I think I rediscovered the wheel. Simply put, I can not use the clock () function to determine the "real" time I spent working in parallel. What do I mean !"ample# A program creates some threads and each one of them will make argv$%& calls to the rand '( function ')ust to do something so that time goes by (. *hen in the end I compute the time recorded by clock '( differences and differences with time'(. +bviously the ratio below is almost two because my machine is dual core. ,ut ... Question: -ow can I measure the e"act time elapsed and not the appro"imation in seconds with time'( .ode#
To plain text
1 2 3 4 5 6 7 8 9 10
$ g++ try_to_time.cpp -pthread -o try $ ./try 50000000 Just started counting! All threads joined! Duration ! ."#"" secs.
Duration $! % started ! % )inished! $0&"'###( seconds a)ter $0&"'##55 seconds a)ter / / (*0. / / (*0.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 19 20
time_t start = start$= start'/ time_t end = end$= end'/ int iterations= i= rc/
21 22 23 24 25 26 27 28 29 30 31 32 33 34
i) ;argc !A $< @ cout ,, B1sage error. 8 am eCpecting one positi:e integer.B ,, endl/ eCit ; </ D iterations A atoi ; arg: > ? </
// create opaEue o.jects. pthread_t % threads A neF pthread_t >012_3456AD7?/ // 2aGe threads Joina.le )or sure. pthread_attr_t attr/ pthread_attr_init ;Hattr</
35 36 37 38 39 40
start
A clocG ;</
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
)or ;i A 0/ i , 012_3456AD7/ i++< @ rc A pthread_create;H;threads>i?<= Hattr= thread_)unction= ;:oid %< Hiterations</ i) ;rc< @ cerr ,, B655K5/ return code )rom pthread_create;< is B ,, rc ,, std!!endl/ eCit ;$</ D D
)or ;i A 0/ i , 012_3456AD7/ i++< pthread_join ; threads >i?= Hstatus </ cout ,, BAll threads joined!B ,, std!!endl/
end
57 58 59 60
A clocG ;</
61 62 63 64 65 66 67 68 69 70 71 72 73 74
- start </
i) ;duration , static_cast,dou.le- ;JMKJN7_I65_76J<< @ cout ,, BOeF iterations. 3ry again Fith a .igger num.er.B ,, endl/ eCit ;'</ D
cout ,, BDuration
,, static_cast,dou.le- ;duration / JMKJN7_I65_76J< ,, B secs.B ,, endl/ cout ,, BDuration $! B ,, endl/ cout ,, B% started ! B ,, start$ ,, B seconds a)ter cout ,, B% )inished! B ,, end$ ,, B seconds a)ter / / (*0.B ,, endl/ / / (*0.B ,, endl/
cout ,, BDuration '! B ,, static_cast,int- ;di))time ; end'= start' < < ,, B secs.B ,, endl/
return 0/
75 76 77 78 79 80
int i/
81 82 83
)or ;i A 0/ i , loops/ i++< rand ;< H+'*/ 5A0D_2AP/ // Just a dummy operation.
pthread_eCit ;01MM</ D