DateTimeHelper R2


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()
        {
            var noww = DateTime.Now;
            var xxx = DateTimeHelper.GetAlignSecondsDateTime(noww, 86400 * 7);
            Console.WriteLine("{1}{0}{2}", ":", xxx, xxx.DayOfWeek);
            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 GetPeriodBeginDate(DateTime time, int days)
        {
            DateTime r = GetAlignSecondsDateTime(time, 86400 * days);
            return r;
        }
        public static DateTime GetPeriodEndDate(DateTime time, int days)
        {
            DateTime r = GetPeriodBeginDate(time, days).AddDays(days - 1);
            return r;
        }
        public static DateTime GetWeekMondayDateTime(DateTime time)
        {
            DateTime r = GetAlignSecondsDateTime(time, 86400 * 7);
            return r;
        }
        public static DateTime GetWeekTuesdayDateTime(DateTime time)
        {
            DateTime r = GetAlignSecondsDateTime(time, 86400 * 7).AddDays(1);
            return r;
        }
        public static DateTime GetWeekWednesdayDateTime(DateTime time)
        {
            DateTime r = GetAlignSecondsDateTime(time, 86400 * 7).AddDays(2);
            return r;
        }
        public static DateTime GetWeekThursdayDateTime(DateTime time)
        {
            DateTime r = GetAlignSecondsDateTime(time, 86400 * 7).AddDays(3);
            return r;
        }
        public static DateTime GetWeekFridayDateTime(DateTime time)
        {
            DateTime r = GetAlignSecondsDateTime(time, 86400 * 7).AddDays(4);
            return r;
        }
        public static DateTime GetWeekSaturdayDateTime(DateTime time)
        {
            DateTime r = GetAlignSecondsDateTime(time, 86400 * 7).AddDays(5);
            return r;
        }
        public static DateTime GetWeekSundayDateTime(DateTime time)
        {
            DateTime r = GetAlignSecondsDateTime(time, 86400 * 7).AddDays(6);
            return r;
        }
        public static DateTime? ParseExactNullableDateTime(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/2496777.html