Need for speed

Imperatorn johan_forsberg_86 at hotmail.com
Thu Apr 1 17:29:24 UTC 2021


On Thursday, 1 April 2021 at 16:52:17 UTC, Nestor wrote:
> I am a python programmer and I am enjoying Dlang and learning 
> some programming insights on the way, thank everyone.
>
> I have no formal education and also program JS and PHP.
>
> Watching a video where a guy programs some simple code in 
> Python and the same code in Go and compares speed I thought 
> that could be some nice exercise for my learning path and 
> successfully ported code to Dlang (hope so)
>
> I was hoping to beat my dear Python and get similar results to 
> Go, but that is not the case neither using rdmd nor running the 
> executable generated by dmd. I am getting values between 
> 350-380 ms, and 81ms in Python.
>
> 1- I am doing something wrong in my code?
> 2- Do I have wrong expectations about Dlang?
>
> Thanks in advance.
>
> This is the video: https://www.youtube.com/watch?v=1Sban1F45jQ
> This is my D code:
> ```
> import std.stdio;
> import std.random;
> import std.datetime.stopwatch : benchmark, StopWatch, AutoStart;
> import std.algorithm;
>
> void main()
> {
>     auto sw = StopWatch(AutoStart.no);
>     sw.start();
>     int[] mylist;
>     for (int number = 0; number < 100000; ++number)
>     {
>         auto rnd = Random(unpredictableSeed);
>         auto n = uniform(0, 100, rnd);
>         mylist ~= n;
>     }
>     mylist.sort();
>     sw.stop();
>     long msecs = sw.peek.total!"msecs";
>     writefln("%s", msecs);
> }
> ```
>
> ```
> import time
> import random
>
> start = time.time()
> mylist = []
> for _ in range(100000):
>     mylist.append(random.randint(0,100))
> mylist.sort()
> end = time.time()
> print(f"{(end-start)*1000}ms")
> ```

Now when I actually read what you wrote I tested moving auto rnd 
= Random(unpredictableSeed) outside the loop and got 481 ms for 
the first version vs 34 ms for the other.

---
     auto sw = StopWatch(AutoStart.no);
     sw.start();
     int[] mylist;

     auto rnd = Random(unpredictableSeed);

     for (int number = 0; number < 100000; ++number)
     {
         auto n = uniform(0, 100, rnd);
         mylist ~= n;
     }

     mylist.sort();
     sw.stop();

     long msecs = sw.peek.total!"msecs";
     writefln("%s", msecs);
---

Also, one thing you could do is to parallelize for even faster 
performance. I can show you how to do that later if you want to.


More information about the Digitalmars-d-learn mailing list