3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【C#】無限ループしながらループ回数を取得する方法

Last updated at Posted at 2022-02-04

結論

forを使った方がコードを読みやすい!!(と思う)のでforがいいんじゃね?と思います。
実行時間はWhileの方がほんのちょっとだけ早いっぽい。

Forを使った方法.cs
for (int roopCount = 1; ; roopCount++)
{
    Console.WriteLine($"{roopCount}回目のループです。");
}
Whileを使った方法.cs
int roopCount = 1;

while (true)
{
    Console.WriteLine($"{roopCount}回目のループです。");

    roopCount++;
}

解説

forを使った方がコードを読みやすい!!(と思う)のでforがいいんじゃねーと思います。
forの終了条件を設定しないことによって無限ループするようにしています。
forなので上記のコードであればroopCountでループ回数を取得できます。
whileはforよりちょっと早いっぽい。

処理速度

forを使ったループ方法で100億回ループするのにかかる時間は15379[ms]でした。

forの時間.cs
var sw = new System.Diagnostics.Stopwatch();

sw.Start();

for (long roopCount = 1; ; roopCount++)
{
    //100億回ループする時間
    if (roopCount == 10000000000)
    {
        sw.Stop();

        Console.WriteLine($"{sw.ElapsedMilliseconds}[ms]");

        break;
    }
}

whileを使ったループ方法で100億回ループするのにかかる時間は15013[ms]でした。

Whileの時間.cs
var sw = new System.Diagnostics.Stopwatch();

sw.Start();

long roopCount = 1;

while (true)
{
    //100億回ループする時間
    if (roopCount == 10000000000)
    {
        sw.Stop();

        Console.WriteLine($"{sw.ElapsedMilliseconds}[ms]");

        break;
    }

    roopCount++;
}

以上!!

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?