Skip to main content
  1. Posts/

intel tbb 学习笔记

Note: This article is available in Chinese only. 本文暂无英文版本。 View original

tbb是**Threading Building Blocks library的缩写,**是一个为开发者提供并行解决方案的库.

先放个文档https://www.threadingbuildingblocks.org/intel-tbb-tutorial

再放一个代码示例:

 1/* ***********************************************
 2Author :111qqz
 3mail: renkuanze@sensetime.com
 4Created Time :2018年07月18日 星期三 14时20分54秒
 5File Name :parallel_for.cpp
 6************************************************ */
 7#include <iostream>
 8#include "tbb/tbb.h"
 9#include <chrono>
10
11using namespace std;
12using namespace tbb;
13
14const int N=1E9+7;
15float a[N+5];
16void Foo(float &x) { x -= 100; }
17void SerialApplyFoo( float a[], size_t n ) {
18for( size_t i=0; i!=n; ++i )
19Foo(a[i]);
20}
21
22class ApplyFoo
23{
24    float *const my_a;
25
26  public:
27    void operator()(const blocked_range<size_t> &r) const
28    {
29        float *a = my_a;
30        for (size_t i = r.begin(); i != r.end(); ++i)
31        {
32
33            Foo(a[i]);
34            //printf("%.4f\n", a[i]);
35        }
36    }
37    ApplyFoo(float a[]) : my_a(a)
38    {
39    }
40};
41
42void ParallelApplyFoo(float a[], size_t n)
43{
44    parallel_for(blocked_range<size_t>(0, n), ApplyFoo(a));
45}
46
47void print(float a[])
48{
49    for (int i = 0; i < N; i++)
50        printf("%.4f%c", a[i], i == 9 ? '\n' : ' ');
51}
52int main()
53{
54    for (int i = 0; i < N; i++)
55        a[i] = 1. * i;
56
57    auto t1 = std::chrono::high_resolution_clock::now();
58    SerialApplyFoo(a,N);
59
60    //ParallelApplyFoo(a, N);
61    auto t2 = std::chrono::high_resolution_clock::now();
62    std::chrono::duration<double, std::milli> fp_ms = t2 - t1;
63     std::cout << "f() took " << fp_ms.count() << " ms, "<<std::endl;
64
65    //print(a);
66    return 0;
67}

编译选项为: g++ -std=c++11 parallel_for.cpp -L/home/sensetime/workspace/graph/3rdparty/tbb/lib/intel64/gcc4.7 -ltbb -o parallel_for

Related