執行個體說明:多進程和多線程 已耗用時間比較

來源:互聯網
上載者:User

多進程:<br />#include <stdio.h><br />#include <time.h></p><p>void function();</p><p>int main()<br />{<br />int j;</p><p> for(j = 0 ; j < 5 ; j++)<br /> {<br /> int pid = fork();<br /> if(pid == 0)<br /> {<br /> clock_t start,end;<br />start = clock();<br />printf("here!/n");<br /> function();<br /> end = clock();<br /> printf("%d/n",end-start);<br /> exit(0);<br /> }<br /> }<br />}</p><p>void function()<br />{<br />int i;<br />for(i = 0 ; i < 1000000000 ; i++)<br />{<br />;<br />}<br />}</p><p>最後已耗用時間:<br />3090000<br />3040000<br />3020000<br />3010000<br />3000000<br />取最大: 3090000</p><p>多線程:<br />#include <stdio.h><br />#include <time.h><br />#include <pthread.h></p><p>void *function();</p><p>int main()<br />{<br />int j;<br />pthread_t tid;<br /> for(j = 0 ; j < 5 ; j++)<br /> {<br />pthread_create(&tid , NULL , (void *)function , NULL);<br /> }<br /> while(1);<br />}</p><p>void *function()<br />{<br />int i;<br />clock_t start,end;<br />start = clock();<br />printf("here!/n");<br />for(i = 0 ; i < 1000000000 ; i++)<br />{<br />;<br />}<br />end = clock();<br />printf("%d/n",end-start);<br />}</p><p>運行結果:<br />150000<br />240000<br />250000<br />250000<br />260000<br />取最大:260000</p><p>結論:多線程比多線程相對系統開銷小,運行要快點<br /> 多線程和多進程已耗用時間比較:

    我的思路是:

一個程式建立5個子進程,並執行一段代碼,分別統計這5個進程啟動並執行時間,取最大的為整個程式已耗用時間(粗數量級估計)

一個程式建立5個子線程,並執行一段代碼,分別統計這5個線程啟動並執行時間,取最大的為整個程式已耗用時間(粗數量級估計)

我不知道我這樣的做法是否合理,不妥之處還請大家指教。或者大家還有什麼其他的計算多進程或多線程已耗用時間的方法。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.