EasyTimer


namespace Microshaoft
{
    using System;
    using System.Timers;
    public class EasyTimer
    {
        private Timer _timer;
        public void Start()
        {
            if (_timer != null)
            {
                _timer.Start();
            }
        }
        private int _intervalSeconds;
        public EasyTimer
                    (
                        int intervalSeconds
                        , int times
                        , Action timerAction
                        , Action<Exception> exceptionAction
                    )
        {
            if (timerAction == null)
            {
                return;
            }
            _intervalSeconds = intervalSeconds * 1000;
            _timer = new Timer(1);
            _timer.Elapsed += new ElapsedEventHandler
                                        (
                                            (x, y) =>
                                            {
                                                TimerActionProcess(times, timerAction, exceptionAction);
                                            }
                                        );
        }
        private void TimerActionProcess(int times, Action timerAction, Action<Exception> exceptionAction)
        {
            if (_timer.Interval < _intervalSeconds)
            {
                _timer.Interval = _intervalSeconds;
            }
            if (timerAction == null)
            {
                return;
            }
            _timer.Enabled = false;
            _timer.Stop();
            DateTime begin;
            do
            {
                begin = DateTime.Now;
                try
                {
                    timerAction();
                }
                catch (Exception e)
                {
                    if (exceptionAction != null)
                    {
                        exceptionAction(e);
                    }
                }
            } while (Math.Abs(DateTimeHelper.SecondsDiffNow(begin)) > times * _intervalSeconds);
            _timer.Start();
            _timer.Enabled = true;
        }
    }
}
namespace Microshaoft
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    using System.IO;
    class Program
    {
        static void Main()
        {
            string r = string.Empty;
            string rootPath = @"e:\temp4";
            Console.WriteLine("测试项目1");
            Console.WriteLine("按任意键测试该项目, 按\"q\"退出该测试项目");
            while ((r = Console.ReadLine()) != "q")
            {
                DateTime now = new DateTime(2012, 5, 12);
                CodeTimer.Time
                    (
                        "写文件"
                        , 1
                        , () =>
                        {
                            Parallel.For
                                    (
                                        0
                                        , 86400
                                        , (x) =>
                                        {
                                            DateTimeHelper.GetAlignSecondsDateTimes<string>
                                                                    (
                                                                        now.AddSeconds(x)
                                                                        , Tuple.Create<long, Func<DateTime, long, DateTime, string, string>>
                                                                                    (
                                                                                        24 * 60 * 60
                                                                                        , (time, alignSeconds, alignedTime, data) =>
                                                                                        {
                                                                                            //Console.WriteLine(alignedTime);
                                                                                            var directory = alignedTime.ToString("yyyy-MM-dd");
                                                                                            var path = (string.IsNullOrEmpty(data) || string.IsNullOrWhiteSpace(data) ? rootPath : data);
                                                                                            path = string.Format
                                                                                                            (
                                                                                                                "{1}{0}{2}"
                                                                                                                , @"\"
                                                                                                                , path.Trim(new char[] { '\\' })
                                                                                                                , directory
                                                                                                            );
                                                                                            if (!Directory.Exists(path))
                                                                                            {
                                                                                                Directory.CreateDirectory(path);
                                                                                            }
                                                                                            return path;
                                                                                        }
                                                                                    )
                                                                        , Tuple.Create<long, Func<DateTime, long, DateTime, string, string>>
                                                                                    (
                                                                                        1 * 60 * 60
                                                                                        , (time, alignSeconds, alignedTime, data) =>
                                                                                        {
                                                                                            //Console.WriteLine(alignedTime);
                                                                                            var directory = alignedTime.ToString("yyyy-MM-dd_HH");
                                                                                            var path = (string.IsNullOrEmpty(data) || string.IsNullOrWhiteSpace(data) ? rootPath : data);
                                                                                            path = string.Format
                                                                                                            (
                                                                                                                "{1}{0}{2}"
                                                                                                                , @"\"
                                                                                                                , path.Trim(new char[] { '\\' })
                                                                                                                , directory
                                                                                                            );
                                                                                            if (!Directory.Exists(path))
                                                                                            {
                                                                                                Directory.CreateDirectory(path);
                                                                                            }
                                                                                            return path;
                                                                                        }
                                                                                    )
                                                                        , Tuple.Create<long, Func<DateTime, long, DateTime, string, string>>
                                                                                    (
                                                                                        5 * 60
                                                                                        , (time, alignSeconds, alignedTime, data) =>
                                                                                        {
                                                                                            var directory = DateTimeHelper.GetDateTimeString(alignedTime, "yyyy-MM-dd_HH-mm");
                                                                                            var path = (string.IsNullOrEmpty(data) || string.IsNullOrWhiteSpace(data) ? rootPath : data);
                                                                                            path = string.Format
                                                                                                            (
                                                                                                                "{1}{0}{2}"
                                                                                                                , @"\"
                                                                                                                , path.Trim(new char[] { '\\' })
                                                                                                                , directory
                                                                                                            );
                                                                                            if (!Directory.Exists(path))
                                                                                            {
                                                                                                Directory.CreateDirectory(path);
                                                                                            }
                                                                                            if (x % 300 != 0)
                                                                                            {
                                                                                                return string.Empty;
                                                                                            }
                                                                                            string file = string.Empty;
                                                                                            string s = DateTimeHelper.GetDateTimeString(alignedTime, "yyyyMMdd-HHmmss");
                                                                                            file = string.Format
                                                                                                                (
                                                                                                                    "{1}{0}{2}.{3}.txt"
                                                                                                                    , @"\"
                                                                                                                    , path
                                                                                                                    , s
                                                                                                                    , Guid.NewGuid().ToString("N")
                                                                                                                );
                                                                                            using (StreamWriter sw = new StreamWriter(File.OpenWrite(file)))
                                                                                            {
                                                                                                sw.WriteLine(s);
                                                                                            }
                                                                                            return string.Empty;
                                                                                        }
                                                                                    )
                                                                    );
                                        }
                                    );
                        }
                    );
                Console.WriteLine("ok");
            }
            Console.WriteLine("测试项目2");
            Console.WriteLine("按任意键测试该项目, 按\"q\"退出该测试项目");
            r = string.Empty;
            while ((r = Console.ReadLine()) != "q")
            {
                CodeTimer.ParallelTime
                            (
                                "GetFiles"
                                , 5
                                , Environment.ProcessorCount
                                , () =>
                                {
                                    //Console.WriteLine(Directory.GetDirectories(@"e:\temp2", "*.*", SearchOption.AllDirectories).Length);
                                    string[] files = Directory.GetFiles(rootPath, "*.*", SearchOption.AllDirectories);
                                    var list = files.ToList();
                                    Parallel.ForEach
                                                (
                                                    list
                                                    , new ParallelOptions()
                                                    {
                                                        MaxDegreeOfParallelism =
                                                            //            1
                                                        Environment.ProcessorCount - 0
                                                    }
                                                    , (x) =>
                                                    {
                                                        string s = File.ReadAllText(x);
                                                    }
                                                );
                                }
                            );
            }
            Console.ReadLine();
        }
    }
}
namespace Microshaoft
{
    using System;
    using System.Diagnostics;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Runtime.InteropServices;
    public static class CodeTimer
    {
        public static void Initialize()
        {
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
            Thread.CurrentThread.Priority = ThreadPriority.Highest;
            Time("", 1, () => { });
        }
        public static void ParallelTime(string name, int iteration, int maxDegreeOfParallelism, Action action)
        {
            InternalIterationProcess
                    (
                        name
                        , iteration
                        , () =>
                        {
                            Parallel.For
                                        (
                                            0
                                            , iteration
                                            , new ParallelOptions()
                                            {
                                                MaxDegreeOfParallelism = maxDegreeOfParallelism
                                                //, TaskScheduler = null
                                            }
                                            , i =>
                                            {
                                                action();
                                            }
                                        );
                        }
                    );
        }
        private static void InternalIterationProcess(string name, int iteration, Action action)
        {
            if (string.IsNullOrEmpty(name))
            {
                return;
            }
            // 1.
            ConsoleColor currentForeColor = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine(name);
            // 2.
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
            int[] gcCounts = new int[GC.MaxGeneration + 1];
            for (int i = 0; i <= GC.MaxGeneration; i++)
            {
                gcCounts[i] = GC.CollectionCount(i);
            }
            // 3.
            Stopwatch watch = new Stopwatch();
            watch.Start();
            ulong cycleCount = GetCycleCount();
            action();
            ulong cpuCycles = GetCycleCount() - cycleCount;
            watch.Stop();
            // 4.
            Console.ForegroundColor = currentForeColor;
            Console.WriteLine
                            (
                                "{0}Time Elapsed:{0}{1}ms"
                                , "\t"
                                , watch.ElapsedMilliseconds.ToString("N0")
                            );
            Console.WriteLine
                            (
                                "{0}CPU Cycles:{0}{1}"
                                , "\t"
                                , cpuCycles.ToString("N0")
                            );
            // 5.
            for (int i = 0; i <= GC.MaxGeneration; i++)
            {
                int count = GC.CollectionCount(i) - gcCounts[i];
                Console.WriteLine
                            (
                                "{0}Gen{1}:{0}{0}{2}"
                                , "\t"
                                , i
                                , count
                            );
            }
            Console.WriteLine();
        }
        public static void Time(string name, int iteration, Action action)
        {
            InternalIterationProcess
                                (
                                    name
                                    , iteration
                                    , () =>
                                    {
                                        for (int i = 0; i < iteration; i++)
                                        {
                                            action();
                                        }
                                    }
                                    );
        }
        private static ulong GetCycleCount()
        {
            ulong cycleCount = 0;
            QueryThreadCycleTime(GetCurrentThread(), ref cycleCount);
            return cycleCount;
        }
        [DllImport("kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool QueryThreadCycleTime(IntPtr threadHandle, ref ulong cycleTime);
        [DllImport("kernel32.dll")]
        static extern IntPtr GetCurrentThread();
    }
}
namespace Microshaoft
{
    using System;
    using System.IO;
    using System.Globalization;
    public static class DateTimeHelper
    {
        public static void GetAlignSecondsDateTimes<T>
                                (
                                    DateTime time
                                    , params Tuple<long, Func<DateTime, long, DateTime, T, T>>[] processAlignSecondsDateTimesFuncs
                                )
        {
            T r = default(T);
            foreach (var x in processAlignSecondsDateTimesFuncs)
            {
                var alignSeconds = x.Item1;
                var alignTime = DateTimeHelper.GetAlignSecondsDateTime(time, alignSeconds);
                if (x.Item2 != null)
                {
                    r = x.Item2(time, alignSeconds, alignTime, r);
                }
            }
        }
        public static bool IsVaildateTimestamp(DateTime timeStamp, int timeoutSeconds)
        {
            long l = SecondsDiffNow(timeStamp);
            return ((l > 0) && (l < timeoutSeconds));
        }
        public static long MillisecondsDiffNow(DateTime time)
        {
            long now = DateTime.Now.Ticks;
            long t = time.Ticks;
            return (t - now) / 10000;
        }
        public static long SecondsDiffNow(DateTime time)
        {
            return MillisecondsDiffNow(time) / 1000;
        }
        public static DateTime GetAlignSecondsDateTime(DateTime time, long alignSeconds)
        {
            long ticks = time.Ticks;
            ticks -= ticks % (10000 * 1000 * alignSeconds);
            DateTime dt = new DateTime(ticks);
            return dt;
        }
        public static string GetDateTimeString(DateTime time, string format)
        {
            return time.ToString(format);
        }
        public static DateTime? ParseExactDateTimeNullable(string text, string format)
        {
            DateTime time;
            DateTime? r = DateTime.TryParseExact
                                        (
                                            text
                                            , format
                                            , DateTimeFormatInfo.InvariantInfo
                                            , DateTimeStyles.None
                                            , out time
                                        ) ? time as DateTime? : null;
            return r;
        }
    }
}

原文地址:https://www.cnblogs.com/Microshaoft/p/2552278.html