. Net4.5 introduces Task-based parallel programming. Parallel Programming is complicated for everyone. This time,. Net introduced a new programming model, and I believe it has aroused everyone's attention. During my learning, I made a small experiment and shared it with you.
In the past, when we were doing performance analysis, we used a timer that was amazing. This time, I found that the System. Diagnostics. Stopwatch class is very useful. It takes only a few steps to solve the time statistics problem:
Stopwatch stop = new Stopwatch ();
Stop. Start (); // Start statistics
Stop. Stop (); // end statistics
Stop. ElapsedMilliseconds // return the elapsed time in milliseconds
Stop. Reset (); // clears the statistical time
Stop. Restart (); // clear and start statistics
Second, I found that writing parallel tasks is much simpler (although extremely basic) than I imagined ).
You only need:
Foreach (var e in data source) {execute Operation}
Convert to the following form to automatically execute the operation tasks of each element in parallel:
Parallet. ForEach (data source, e =>{ execute Operation })
Parallet is a class in the space of System. Threading. Tasks.
If the execution is not a foreach loop, but a for loop, it is also possible:
For (int I = 0; I <1000; I ++) {execution operation }=> Parallet. For (0, 1000, I =>{ execution operation })
It's so easy! I believe that those who don't really want to understand parallel programming can also slightly improve their program concurrency through the above syntax.
Then I made a performance analysis on my E7200 dual-core cpu. When each task runs for about 1 ms, the parallel ratio synchronization is: 1.3: 1; when 10 ms, 1.7: 1; 100: 1 in 1.9 milliseconds. if it is less than 1 ms, the performance will be inferior to synchronization.
In view of rp, most of the code I write is run at extremely high speed, so this parallel can be used rarely. But I hope it will be useful to everyone.
Finished!