Sample code for asynchronous performance tests in. Net

Source: Internet
Author: User
Haven't written a blog for a long time, this year to do the product companies have just opened a conference, a little idle down, think we do the product has no performance optimization space, then thought of. NET is asynchronous to optimize performance, but how much can it improve? Just have a friend doing asynchronous performance testing in various languages (for asynchronous and synchronous issues, refer to the customer "AIO vs. Bio interface Performance Comparison"), so I wrote a test program for C # today.

First, build an ASP. NET MVC Webapi project, adding two methods to the default controller values:


GET api/values?sleeptime=10         [httpget] public         async task<string> Executeaio (int sleeptime)         {                    await Task.delay (sleeptime);                    return  "Hello world," + Sleeptime;        }        [HttpGet]                GET api/values?sleeptime2=10 Public        string Executebio (int sleepTime2)        {            System.Threading.Thread.Sleep (sleepTime2);                        Return "Hello World," + sleepTime2;        }

Then, set up a console program to test the Web API:


 Class Program {static void Main (string[] args) {Console.WriteLine ("Press any key to start the test webapi:http://l            Ocalhost:62219/api/values?sleeptime={int} ");                        Console.Write ("Please enter the number of threads:");                        int threadnum = 100; Int.                        TryParse (Console.ReadLine (), out threadnum);            while (Test (threadnum));            Console.ReadLine ();        Console.ReadLine ();                        } private static bool Test (int tasknumber) {Console.Write ("Enter the sleep time of this API method (MS), enter non-digital content to exit:");                        string input = Console.ReadLine ();                        int sleeptime = 50; if (!int.            TryParse (input, out sleeptime)) return false;            HttpClient client = new HttpClient (); Client.                        baseaddress = new Uri ("http://localhost:62219/"); var result = client. Getstringasync ("api/values?sleeptime=" + input).            Result; Console.wriTeline ("result:{0}", Result);            int tasknumber = 1000;            Console.WriteLine ("{0} times BIO (sync) test (sleep {1} milliseconds):", Tasknumber, Sleeptime);            System.Diagnostics.Stopwatch SW = new System.Diagnostics.Stopwatch (); Sw.            Start ();                        task[] Taskarr = new Task[tasknumber]; for (int i = 0; i < Tasknumber; i++) {Task task = client.                Getstringasync ("api/values?sleeptime2=" + sleeptime);            Taskarr[i] = task;            } task.waitall (Taskarr); Sw.                        Stop (); Double useTime1 = sw.            Elapsed.totalseconds;            Console.WriteLine ("Time-consuming (seconds): {0},qps:{1,10:f2}", useTime1, tasknumber/usetime1); Sw.            Reset ();            Console.WriteLine ("{0} times AIO (async) Test (Sleep {1} milliseconds):", Tasknumber, Sleeptime); Sw.                        Start (); for (int i = 0; i < Tasknumber; i++) {Task task = client. Getstringasync ("Api/values?Sleeptime= "+ sleeptime);            Taskarr[i] = task;            } task.waitall (Taskarr); Sw.                        Stop (); Double useTime2 = sw.            Elapsed.totalseconds;                        Console.WriteLine ("Time-consuming (seconds): {0},qps:{1,10:f2}", UseTime2, tasknumber/usetime2);        return true; }    }

View Code

In fact, the following lines of code are mainly:


HttpClient client = new HttpClient (); client. baseaddress = new Uri ("http://localhost:62219/"); var result = client. Getstringasync ("api/values?sleeptime=" + input). Result;

Note that you may need to use NuGet to add the following package:

Microsoft.AspNet.WebApi.Client

Finally, run the test with the following results:


Press any key to start the test webapi:http://localhost:62219/api/values?sleeptime={int} Please enter the number of threads: 1000 Enter the sleep time (in milliseconds) for this API method, Enter non-digital content exit: 10Result: "Hello world,10" 1000 Times BIO (sync) test (sleep 10 milliseconds): time-consuming (seconds): 1.2860545,qps:    777.571 AIO (asynchronous) test (sleep 10 milliseconds) : Time-consuming (seconds): 0.4895946,qps:   2042.51 Enter the sleep time (in milliseconds) of this API method, enter non-digital content exit: 100Result: "Hello world,100" 1000 Times BIO (sync) test (sleep 100 ms ): Time-consuming (seconds): 8.2769307,qps:    120.821 AIO (asynchronous) test (sleep 100 milliseconds): time-consuming (seconds): 0.5435111,qps:   1839.89

Originally wanted to try to test 10,000 threads, but error.

The above test results, the QPS is not high, but because of the use of iisexpress, different Web server software performance is not the same, so we have to compare the results of the in-process QPS, and then create a new console program, the code is as follows:


 Class Program {static void Main (string[] args) {Console.WriteLine ("Press any key to start test");                        Console.Write ("Please enter the number of threads:");                        int threadnum = 100; Int.                        TryParse (Console.ReadLine (), out threadnum);            while (Test (threadnum));            Console.ReadLine ();        Console.ReadLine ();                        } private static bool Test (int tasknumber) {Console.Write ("Enter the sleep time of this API method (MS), enter non-digital content to exit:");                        string input = Console.ReadLine ();                        int sleeptime = 50; if (!int.                        TryParse (input, out sleeptime)) return false; var result = Executeaio (sleeptime).            Result;                        Console.WriteLine ("Result:{0}", Result);            int tasknumber = 1000;            Console.WriteLine ("{0} times BIO (sync) test (sleep {1} milliseconds):", Tasknumber, Sleeptime); System.Diagnostics.Stopwatch SW = nEW System.Diagnostics.Stopwatch (); Sw.            Start ();                        task[] Taskarr = new Task[tasknumber]; for (int i = 0; i < Tasknumber; i++) {Task task = task.run<string> (() = Executebio (                Sleeptime));            Taskarr[i] = task;            } task.waitall (Taskarr); Sw.            Stop (); Double useTime1 = sw.            Elapsed.totalseconds;            Console.WriteLine ("Time-consuming (seconds): {0},qps:{1,10:f2}", useTime1, tasknumber/usetime1); Sw.            Reset ();            Console.WriteLine ("{0} times AIO (async) Test (Sleep {1} milliseconds):", Tasknumber, Sleeptime); Sw.            Start ();                for (int i = 0; i < Tasknumber; i++) {Task task = Executeaio (sleeptime);            Taskarr[i] = task;            } task.waitall (Taskarr); Sw.            Stop (); Double useTime2 = sw.            Elapsed.totalseconds; Console.WriteLine ("Time-consuming (seconds): {0},qps:{1,10:f2}", UseTime2, Tasknumber/usetime2);        return true;             } public static Async task<string> Executeaio (int sleeptime) {await task.delay (sleeptime);        Return "Hello World," + sleeptime;                        } public static string Executebio (int sleepTime2) {System.Threading.Thread.Sleep (sleepTime2); Task.delay cannot be used inside a non-async method, otherwise deadlock//task.delay (sleepTime2) may be deadlocked.            Wait ();        Return "Hello World," + sleepTime2; }    }

View Code

Note that the key code has only the following two methods:


public static async task<string> Executeaio (int sleeptime)        {            await task.delay (sleeptime);                    Return "Hello World," + Sleeptime;        }        public static string Executebio (int sleepTime2)        {            System.Threading.Thread.Sleep (sleepTime2);                        Task.delay cannot be used inside a non-async method, otherwise deadlock                        //task.delay (sleepTime2) may be deadlocked. Wait ();            Return "Hello World," + sleepTime2;        }

These two methods are the same as the Webapi test method code, but the calling code is slightly different:

Synchronous invocation:


task[] Taskarr = new Task[tasknumber];            for (int i = 0; i < tasknumber; i++)            {                Task task = task.run<string> (() = Executebio (Sleeptime));                Taskarr[i] = task;            }            Task.waitall (Taskarr);

Asynchronous invocation:


for (int i = 0; i < tasknumber; i++)            {                Task task = Executeaio (sleeptime);                Taskarr[i] = task;            }            Task.waitall (Taskarr);

As can be seen here, when testing, synchronous and asynchronous calls, the client code is used by multi-threading, the main difference is that the asynchronous method uses the Async/await statement.

The following are the results of non-web, in-process asynchronous multithreading and synchronous Multithreading:


Please enter the number of threads: 1000 Enter the sleep time (in milliseconds) of this API method, enter non-digital content exit: 10result:hello world,101000 BIO (sync) test (sleep 10 ms): Time Elapsed (seconds): 1.3031966,qps:    767.341 AIO (asynchronous) test (sleep 10 milliseconds): time-consuming (seconds): 0.026441,qps:  37820.05 Enter the sleep time (in milliseconds) of this API method and enter non-digital content to exit: 100result:hello World , 1.001 million BIO (sync) test (sleep 100 ms): Time-consuming (seconds): 9.8502858,qps:    101.521 AIO (asynchronous) test (sleep 100 milliseconds): time-consuming (seconds): 0.1149469,qps:   8699.67 Enter the number of threads: 10000 Enter the sleep time (in milliseconds) of this API method and enter non-digital content to exit: 10result:hello world,1010000 BIO (sync) test (sleep 10 ms): Time consuming (seconds): 7.7966125, QPS:   1282.611 AIO (asynchronous) test (sleep 10 milliseconds): time-consuming (seconds): 0.083922,qps:119158.27 Enter the sleep time (in milliseconds) of this API method and enter non-digital content to exit: 100Result: Hello world,10010000 times BIO (sync) test (sleep 100 ms): Time-consuming (seconds): 34.3646036,qps:    291.001-time AIO (asynchronous) test (sleep 100 ms) : Time-consuming (seconds): 0.1721833,qps:  58077.64

The results show that. NET program to open 10,000 tasks (not 10,000 native threads, you need to consider thread pool threads), the Async method has more than 100,000 QPS, and the synchronization method only 1000多 points, the performance gap is still very large.

Note: The test environment for the above test results is

Intel i7-4790k cpu,4 Core 8 thread, Memory 16GB,WIN10 Enterprise Edition

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.