zsh-users
 help / color / mirror / code / Atom feed
From: Oliver Kiddle <opk@zsh.org>
To: Ray Andrews <rayandrews@eastlink.ca>
Cc: Zsh Users <zsh-users@zsh.org>
Subject: Re: run time of math problem
Date: Sat, 20 Mar 2021 00:52:39 +0100	[thread overview]
Message-ID: <41359-1616197959.973399@0dqq.OWmi.jXTb> (raw)
In-Reply-To: <a1c6d13a-7a04-fba4-4419-7eccbf013824@eastlink.ca>

Ray Andrews wrote:
>      for ((level=1; level<100; level++)); do
>          sum=
>          for ((terms=level; terms; terms--)); do
>
>              # 'remainder' calculation done directly here:
>              sum+=$(( ( (level - 1.0) / level )**(terms - 1) ))
>          done
>          divided=$(( sum * (1.0 / level) ))
>          echo for level: $level, survival: $divided
>     done
>
> ... I'd expect the thing to run a teeny bit faster but in fact it
> runs about 15% slower.  Is that explicable?  Does zsh prefer

Given that the latter approach has moved the remainder calculation
inside a loop and it needs to be repeated 50 times (on average), it
should be no surprise that it is slower.

If you want to optimise for speed, avoid string conversions and do, e.g.
  (( divided = sum * (1.0 / level) ))

You also may want to make sure to declare some of the variables as float
or integer or whatever. The sum+= line might end up being a string
concatenation if not.

Oliver


  parent reply	other threads:[~2021-03-19 23:53 UTC|newest]

Thread overview: 6+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2021-03-19 23:18 Ray Andrews
2021-03-19 23:46 ` Lawrence Velázquez
2021-03-19 23:51   ` Ray Andrews
2021-03-19 23:52 ` Oliver Kiddle [this message]
2021-03-20  2:40   ` Ray Andrews
2021-03-20  3:59     ` Lawrence Velázquez

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=41359-1616197959.973399@0dqq.OWmi.jXTb \
    --to=opk@zsh.org \
    --cc=rayandrews@eastlink.ca \
    --cc=zsh-users@zsh.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
Code repositories for project(s) associated with this public inbox

	https://git.vuxu.org/mirror/zsh/

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).