在C#代码上使用GPU / TPL加快速度,耗时40分钟

时间:2019-06-09 09:54:28

标签: c# multithreading performance parallel-processing task-parallel-library

我想对文本文件执行一些计算,该文本文件每行有1个数字“ 0,1” ,几乎有 100万行。

我想检查一个序列在整个文件中存在多少次,并根据sequence length来确定一个序列,例如我的文件是:

  

01100101011 ....最多100万(每个数字都换行)

代码

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

public class Program
{
    static void Main(string[] args)
    {
        Stopwatch time = new Stopwatch();
        time.Start();
        try
        {
            // I have hard coded fileName and Sequence Length that i am taking from user
            string data = "", fileName = "10.txt";  // this file has almost 1 Million records
            int first = 0, last = 0;

            // reads data and make a string of that data
            // which means "data" = "1001011001010100101 .... upto 1 million"
            data = string.Join("", File.ReadAllLines(fileName)); 
            last = Convert.ToInt32("15"); // sequence length
            int l = data.Length;    // calculates it one time so that dont have to do it everytime

            //so why i create List is because sometime Array dont get fully used to its length
            // and get Null values at the end
            List<string> dataList = new List<string>();
            while (first + last < l+1)
            {
                dataList.Add((data.Substring(first, last)));
                first++;
            }
            // converts list to Array so array will have values and no Null
            // and will use Array.FindAll() later
            string[] dataArray = dataList.ToArray(), value;

            // get rready a file to start writing on
            StreamWriter sw = new StreamWriter(fileName.Substring(0, fileName.Length - 4) + "Results.txt");

            //THIS IS THE PART THATS TAKING around 40 minutes
            for (int j = 0; j < dataArray.Length; j++)
            {
                // finds a value in whole array and make array of that finding 
                value = Array.FindAll(dataArray, str => str.Equals(dataArray[j]));
                // value.Length means the count of the Number in the whole array
                sw.WriteLine(value.Length);
            }
            sw.Close();
            time.Stop();
            Console.WriteLine("Time : " + time.Elapsed);
            Console.ReadLine();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception " + ex.StackTrace);
            Console.ReadLine();
        }
    }
}

我设置了sequence length = 3,现在我的程序做了一个数组:

  

dataArray = {“ 011”,“ 110”,“ 100”,“ 001”,“ 010”,“ 101”,“ 011”}

通过使用String.Substring()。现在,我只想计算数组元素的频率

结果.txt文件中的数据

  

011-2

     

110-0

     

100-0

     

001-0

     

010-0

     

101-0

     

011-2

现在看来似乎很简单,但事实并非如此,我不能转换它int,因为它是一个序列,我不想丢失序列前面的零。

现在,我的程序必须循环 1百万个(每个元素)X 1百万个(与数组的每个元素比较)= 1万亿次次。大约要花40分钟。我想知道如何快速实现它, Parallel.For,TPL 我不知道他们如何使用它们。因为它应该在几秒钟内完成。

我的系统规格

  

32 GB RAM

     

i7- 5820k 3.30 GHz

     

64位

     

2个nvidia gtx 970

2 个答案:

答案 0 :(得分:2)

如果我正确理解了您的代码和问题,则需要在文本上“滑动窗口”(在原始代码中长度为N,last),并计算每个子字符串在其中存在多少次文字。

如果是的话,下面的代码可以在0.292秒左右的时间内完成一个百万字符文件,而且您根本不需要并行性或GPU。

这里的想法是,当我们在文本上滑动窗口时,将块计数计入Dictionary

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

public class Program
{
    static Dictionary<string, int> CountChunks(string data, int chunkLength)
    {
        var chunkCounts = new Dictionary<string, int>();
        var l = data.Length;
        for (var i = 0; i < l - chunkLength; i++)
        {
            var chunk = data.Substring(i, chunkLength);
            int count = 0;
            chunkCounts.TryGetValue(chunk, out count);
            chunkCounts[chunk] = count + 1;
        }
        return chunkCounts;
    }
    static void Main(string[] args)
    {
        var time = new Stopwatch();
        time.Start();
        var fileName = "10.txt";
        var data = string.Join("", File.ReadAllText(fileName));
        var chunkCounts = CountChunks(data, 15);
        using (var sw = new StreamWriter(fileName.Substring(0, fileName.Length - 4) + "Results.txt"))
        {
            foreach (var pair in chunkCounts)
            {
                sw.WriteLine($"{pair.Key} - {pair.Value}");
            }
        }
        time.Stop();
        Console.WriteLine("Time : " + time.Elapsed);
    }
}

输出10Results.txt看起来像

011100000111100 - 34
111000001111000 - 37
110000011110001 - 27
100000111100010 - 28
000001111000101 - 37
000011110001010 - 36
000111100010100 - 44
001111000101001 - 35
011110001010011 - 41
111100010100110 - 42

编辑:这是等效的Python程序。慢了约0.9秒。

import time
from collections import Counter

t0 = time.time()
c = Counter()
data = ''.join(l for l in open('10.txt'))
l = 15
for i in range(0, len(data) - l):
    c[data[i : i + l]] += 1

with open('10Results2.txt', 'w') as outf:
    for key, value in c.items():
        print(f'{key} - {value}', file=outf)

print(time.time() - t0)

答案 1 :(得分:1)

For循环将给您带来糟糕的性能,因为它必须循环进行一百万个字符串比较。 我建议使用字典而不是列表来将序列存储为键并计算为值。 与while / for循环相比,它应该为您提供更好的性能。 您需要做的只是针对性能角度进行一些调整,除非您将其作为唯一目的,否则可能甚至不需要利用GPU / TLP运行时。 以下内容可以帮助您顺利进行。

       string keyString = string.Empty;
       Dictionary<string,int> dataList = new Dictionary<string,int>;
        while (first + last < l+1)
        {
            keyString = data.Substring(first, last);
            if(dataList.ContainsKey(keyString)
               {
                 dataList[keyString] = dataList[keyString] + 1; 
               }
             else
               {
                 dataList.Add(keyString,1);
               }
            first++;
        }

您需要的其余代码就是打印该词典。