hagard
hagard

Reputation: 31

Code for parallel programming c# and running time

For compare running time in parallel and serial computing mode,i convert a word with lowercase characters to uppercase .For parallel mode ,i run 2 threads and get running time for it. Now running time in parallel is greater than serial. What is wrong in my code???

    public void thread1()
    {

        for (int k = 0; k < Len; k = k + 2)
        {
            string sr1 =chars[k].ToString();
            pchars[k] = sr1.ToUpper();
        }
    }
    public void thread2()
    {
        for (int q = 1; q < Len; q = q + 2)
        {
            string sr2 = chars[q].ToString();
            pchars[q] = sr2.ToUpper();
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {   
        read_array();
        var time2 = Stopwatch.StartNew();
        Thread t1 = new Thread(new ThreadStart(thread1));
        Thread t2 = new Thread(new ThreadStart(thread2));
        t1.Start();
        t2.Start();
        time2.Stop();
        lbl1.Text = (time2.Elapsed.TotalMilliseconds).ToString("ms");
        Thread.Sleep(1);

    }



}

Upvotes: 1

Views: 601

Answers (1)

A few points here: first, as DangerZone indicated in the comments, adding threads has some overhead, so you need to make sure that whatever you're doing on the thread is actually CPU-intensive enough to justify the overhead of the threads. In this case, it looks like it's not.

Secondly, the following test is completely invalid:

    var time2 = Stopwatch.StartNew();
    Thread t1 = new Thread(new ThreadStart(thread1));
    Thread t2 = new Thread(new ThreadStart(thread2));
    t1.Start();
    t2.Start();
    time2.Stop();

All you're actually measuring here is how long it takes to create and start the threads, not how long it actually takes to complete the tasks the threads are actually running.

Third, for this kind of "one-time" task where you're just doing something once and then throwing it away, you probably want to use Task.Run or the thread pool.

Upvotes: 1

Related Questions