有趣的 Parallel.For

為了營造在自己 i7 NB 上 SQL Server 2008 R2 Utility 的 CPU 使用率過高,讓分析圖看起來有點效果:

image

於是透過 .NET Framework 4.0 的 Parallel.For 模擬前端多 AP 存取,果然大操了 SQL Server 一頓 ^^

using System.Text;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.Threading;
using System.Data.SqlClient;
using System.Diagnostics;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        const string strCnn = @"Data Source=.I2;Initial Catalog=Northwind;Integrated Security=SSPI;Application Name=Test";
        public Form1()
        {
            InitializeComponent();
            RunSQL(@"IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tb]’) AND type in (N’U’))
                        DROP TABLE [dbo].[tb]");
            RunSQL(@"CREATE TABLE tb
                    (
                        PK BIGINT IDENTITY PRIMARY KEY,
                        InsertValue INT DEFAULT(0),
                        InsertTime DATETIME2(7) DEFAULT(SYSDATETIME())
                    )"
                );
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Stopwatch sw = new Stopwatch();
            sw.Reset();
            sw.Start();

            Parallel.For(0,10, j =>
                {
                    for (int i=0; i < 100000; i++)
                    {
                        RunSQL("INSERT tb(InsertValue) VALUES(" + j.ToString() + ")");
                    }
                }
                );
            sw.Stop();
            MessageBox.Show("Ok 共花費 " + sw.ElapsedMilliseconds.ToString() + " 微秒");
        }

        private void RunSQL(string strSQL)
        {
            using (SqlConnection cnn = new SqlConnection(strCnn))
            {
                cnn.Open();
                SqlCommand cmd = new SqlCommand(strSQL, cnn);
                cmd.ExecuteNonQuery();
                cnn.Close();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Stopwatch sw = new Stopwatch();
            sw.Reset();
            sw.Start();
            for (int i = 0; i < 100000; i++)
            {
                RunSQL("INSERT tb(InsertValue) VALUES(1)");
            }
            sw.Stop();
            MessageBox.Show("Ok 共花費 " + sw.ElapsedMilliseconds.ToString() + " 微秒");

        }
    }
}

啟動平行於否,在 i7 的時間差了 6 倍,可能我的 DB 都在 SSD 上,否則 HD 若成為最大瓶頸,則時間差應不會那麼大

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

Google+ photo

You are commenting using your Google+ account. Log Out / 變更 )

連結到 %s

%d 位部落客按了讚: