<p><a href="https://github.com/kavehmz/prime">https://github.com/kavehmz/prime</a></p>
<p>I wrote a prime number generator while ago when I was learning Go (Sieve method). Then I got time to improve it a bit (Segmented Sieve).</p>
<p>Then I ran pprof and improved the performance as much as I could.</p>
<p>Can anyone suggest any change that improves it even further? Not a new method but any Go improvement.</p>
<hr/>**评论:**<br/><br/>dlsniper: <pre><p>I might also add: do not call GOMAXPROCS from a library as you will affect the main application running in ways the author has no control over.</p></pre>kavehmz: <pre><p>True, No need.</p></pre>abcded1234234: <pre><p>Have you tried to compare performance of a single threaded version to your parallel version. What are the results?</p>
<p>Try experimenting with the segment size, if a single segment can fit into L1 cache the code will run faster.</p>
<p>Some advice not related to performance:</p>
<ul>
<li> do not call <code>runtime.GOMAXPROCS(cores)</code> from your functions. This is no longer needed in Go 1.5+</li>
<li>consider using sync.WaitGroup instead of channels</li>
<li>why are you calling <code>next <- true</code> NumCPU() times? This doesn't look right.</li>
<li>build your program with <code>-race</code>flag and run it to make sure there are no race conditions</li>
</ul></pre>kavehmz: <pre><p>next <- true is for waiting for last goroutines to end.
Sure, I will try sync and see if it helps. But I can't imagine how.
Thanks, will check -race too.</p></pre>kavehmz: <pre><p>single threaded if you mean no go routine, I checked and it was slower.</p></pre>motojo: <pre><p>Using a single thread, this is what I wrote based off my intern's way of counting the number of prime numbers: <a href="https://gist.github.com/josephspurrier/c3073854dd718f5c8021" rel="nofollow">https://gist.github.com/josephspurrier/c3073854dd718f5c8021</a></p></pre>kavehmz: <pre><p>This is slower. I want to improve the performance.</p>
<p>I also I want to return the numbers.</p></pre>kavehmz: <pre><p>Also you are doing it non-segmented way that will use much more memory.</p>
<p><a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow">https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes</a></p>
<p>Check the Segmented Sieve part.</p>
<p>Anyway I am looking for Go suggestions/tricks.</p></pre>
![](https://static.golangjob.cn/static/img/banner.png)