zoukankan      html  css  js  c++  java
  • 实际使用VS 2010和.NET 4.0新特性——并行编程

    在.NET 4.0中,一个重要的新特性就是并行编程。目前提供的编程模型如下图所示(来自MSDN):

    .NET Parallel Programming Architecture

    提供了如下几个函数库和工具来实现(辅助)并行编程:

    Task Parallel Library(任务并行库)

    Includes parallel implementations of for and foreach loops ( For and For Each in Visual Basic). Enables you to define concurrent, asynchronous tasks without having to work with threads, locks, or the thread pool.

    Parallel LINQ (PLINQ)

    A parallel implementation of LINQ to Objects that significantly improves performance in many scenarios.

    Data Structures for Parallel Programming(并行编程数据结构)

    Includes high-performance collection classes that are lock-free and thread-safe. Also includes other lightweight objects for synchronization and lazy initialization.

    Parallel Diagnostic Tools(并行诊断工具)

    Includes debugger windows for tasks and parallel stacks, and concurrency views in the Visual Studio Team System Profiler that you can use to debug and to tune the performance of parallel code.

    其中,任务并行库(TPL)是使用最直接,最方面的函数库了。如果你的代码涉及的数据能够很容易的划分为独立的小块任务(而且相关的资源,也不容易产生冲突,最好是共享的资源只读,要写的资源可以分离/分开写入,不关心顺序),那么一句话就可以实现并行计算。

    今天小试了一下Parallel.ForEach。我现有一个程序的功能是这样的:读取一组文件(它们格式一致)里面的内容,转换为保存另外一种格式,并同时把所有文件中的某些信息保存到一个对象集合中。由于我这样的操作,只是逐一处理每个文件,要生成的对象集合也是只写入(不修改,不删除),而且也不用关心顺序。所以真的一句话就搞定了。示例代码如下:

    int t1 = Environment.TickCount;
    //foreach (var item in elcd2.AllProcesses)
    //{
    //    CreateInventoryDoc(item);
    //}
    //234,242

    Parallel.ForEach(elcd2.AllProcesses, item => CreateInventoryDoc(item));
    //126,131

    int t2 = Environment.TickCount;

    可以看到,使用并行算法(我的是双核)所用时间减少到一半。以后转换这些数据,干等的时间就减半了。

    另外发现一个有趣的事情,如果不用并行的话,操作系统(Windows 7的新功能)会把计算量平均分到两个核上。

    分享到: 更多
  • 相关阅读:
    响应式css样式
    组件 computed 与 vuex 中 getters 的使用,及 mapGetters 的使用,对象上追加属性,合并对象
    nginx 错误集锦
    动态的添加路由
    NProgress的使用 及 路由 token 定向的使用
    token的解码及 判断值不为空的方法
    nginx 的使用
    IT公司100题-tencent-打印所有高度为2的路径
    测试
    Objective-C 与 C++ 的异同
  • 原文地址:https://www.cnblogs.com/redmoon/p/1637608.html
Copyright © 2011-2022 走看看