пятница, 29 февраля 2008 г.

Сравнение производительность С#,C,C++ часть 1, код на C#

Задумал я страшное - сравнить производительность чистого С, С++ (с использованием STL и boost) и С# на основании задачи из заметки Разединяем строки...обьединяем строки.

Напомню задачу:
нужно из таких строк: "word1-word2", "word3-word4", "word5-word6"
получить вот такую строку:
word1:word2:word3:word4:word5:word6

Для сравнения производительности время выполнения замерял с помощью QueryPerformanceCounter, просто потому что этот способ одинаков для С# и С++.

Основной код - код, делающий всю работу:

string r = ":".join(array1.SelectMany(x => x.Split('-')));


Весь исходный код на C#

using System;

using System.Linq;

using System.Collections.Generic;

using System.Runtime.InteropServices;

 

namespace MainProgramm

{

    static class string_extentions

    {

        public static string join(this string a, IEnumerable<string> elems)

        {

            string result = "";

            foreach (string elem in elems) {

                if (result.Length != 0)

                    result += a;

                result += elem;

            }

            return result;

        }

    }

    internal class HiPerfTimer

    {

        [DllImport("Kernel32.dll")]

        private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

 

        [DllImport("Kernel32.dll")]

        private static extern bool QueryPerformanceFrequency(out long lpFrequency);

 

        private long startTime, stopTime;

        private long freq;

        public HiPerfTimer(){QueryPerformanceFrequency(out freq);}

        public void    start   (){QueryPerformanceCounter(out startTime);}

        public void    stop    (){QueryPerformanceCounter(out stopTime);}

        public double   duration{

            get{return (double)(stopTime - startTime) / (double)freq;}

        }

    }

 

    class Program

    {

        static void Main(string[] args){

            string[] array1 = { "word1-word2", "word3-word4", "word5-word6", "word7-word8", "word9-word0" };

            HiPerfTimer pt = new HiPerfTimer();

            pt.start();

            for (int i = 0; i < 10000; ++i){

                string r = ":".join(array1.SelectMany(x => x.Split('-')));

            }

            pt.stop();

 

            Console.WriteLine("C# - {0} sec\n", pt.duration); // print the duration of the timed code

        }

    }

}

Комментариев нет: