Skip to content
Rain Hu's Workspace
Go back

[CS] Sample cost for performance test

Rain Hu

Sample code for stop watch

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Data.Common;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Threading.Tasks;

namespace Rainspace.PlayGround
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            System.Console.WriteLine("==============Accumulate1==============");
            System.Console.WriteLine("Result: " + Accumulate(0, 100, 0));
            sw.Stop();
            System.Console.WriteLine("Time cost: " + (sw.ElapsedTicks/1.0e6).ToString() + "ms");
            sw.Reset();
            sw.Start();
            System.Console.WriteLine("==============Accumulate2==============");
            System.Console.WriteLine("Result: " + Accumulate(0, 100, 0));
            sw.Stop();
            System.Console.WriteLine("Time cost: " + (sw.ElapsedTicks/1.0e6).ToString() + "ms");
        }
        public static int Accumulate(int begin, int end, int sum = 0)
        {
            int res = sum;
            if (end < begin) return Accumulate(end, begin, sum);
            for (int i = begin; i < end; i++) 
            {
                res += i;
            }
            return res;
        }
        public static int Accumulate2(int begin, int end, int sum = 0)
        {
            int res = (begin + end) * (end - begin) / 2;
            return res + sum;
        }
    }
}

Share this post on:

Previous
[DXP] 使用 Visual Studio 對 Spotfire 開發進行環境設置
Next
[IT] 關聯模式的五大鍵 Super key、Candidate Key、Primary Key、Alternate Key、Foreign Key