C# 增量时间实现

标签 c# time timedelta

这是我尝试制作 2D 粒子模拟的代码片段

static long lastTime = 0;
static double GetDeltaTime()
{
    long now = DateTime.Now.Millisecond;
    double dT = (now - lastTime); // / 1000
    lastTime = now;
    Console.WriteLine(dT);
    return dT;
}

很明显,它会返回自上次调用该方法以来的时间(以毫秒为单位)。唯一的问题,这是它打印的内容

393
1
0
0
0
0
0
0
0
0
0
...

好吧,也许这只是因为每次通过不到一毫秒。所以我把它改成了

    static long lastTime = 0;
    static double GetDeltaTime()
    {
        long now = DateTime.Now.Ticks; // Changed this to ticks
        double dT = (now - lastTime); // / 1000
        lastTime = now;
        Console.WriteLine(dT);
        return dT;
    }

但仍然打印

6.35476136625848E+17
20023
0
0
0
0
0
0
...

如果“粒子模拟器”不能很好地指示我的程序有多复杂,我只想说,它需要比 0 ticks 更长的时间来完成一次传递!

那么这里发生了什么?

-------- 代码引用------ 这里全类仅供引用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace _2D_Particle_Sim
{
    static class Program
    {
        public static Particle2DSim pSim;
        static Form1 form;
        public static Thread update = new Thread(new ThreadStart(Update));

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]

        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            form = new Form1();

            pSim = new Particle2DSim(form);
            pSim.AddParticle(new Vector2(-80, -7), 5);
            pSim.AddParticle(new Vector2(8, 7), 3);

            Console.WriteLine("Opening Thread");

            Program.update.Start();

            Application.Run(form);

            // System.Threading.Timer timer;
            // timer = new System.Threading.Timer(new TimerCallback(Update), null, 0, 30);
        }

        static void Update()
        {
            GetDeltaTime();
            while (true)
            {
                pSim.Update(GetDeltaTime());
            }
        }

        static long lastTime = 0;
        static double GetDeltaTime()
        {
            long now = DateTime.Now.Ticks;
            double dT = (now - lastTime); // / 1000
            lastTime = now;
            Console.WriteLine(dT);
            return dT;
        }
    }
}

此外,如果我对我的代码有多复杂的类比仍然不够,这里是 Particle2DSim 类的更新方法

    public void Update(double deltaTime)
        {
              foreach (Particle2D particle in particles)
              {
                  List<Particle2D> collidedWith = new List<Particle2D>();

                  Vector2 acceleration = new Vector2();
                  double influenceSum = 0;

                  // Calculate acceleration due to Gravity
                  #region Gravity
                  foreach (Particle2D particle2 in particles)
                  {
                      double dist2 = particle.position.Distance2(particle.position);
                      double influence = dist2 != 0 ? particle2.mass / dist2 : 0;
                      acceleration.Add(particle.position.LookAt(particle2.position) * influence);
                      influenceSum += influence;

                      if (dist2 < ((particle.radius + particle2.radius) * (particle.radius + particle2.radius)) && dist2 != 0)
                      {
                          collidedWith.Add(particle2);
                      }
                  }
                  acceleration.Divide(influenceSum);
                  #endregion

                  particle.Update(deltaTime);

                  // Handle Collisions
                  #region Collisions
                  if (collidedWith.Count > 0)
                  {
                      Console.WriteLine("Crash!");

                      double newMass = 0;
                      double newRadius = 0;

                      Vector2 newPosition = new Vector2();
                      Vector2 newVelocity = new Vector2();

                      newMass += particle.mass;
                      newRadius += Math.Sqrt(particle.radius);

                      newPosition += particle.position;

                      newVelocity += particle.velocity * particle.mass;

                      particles.Remove(particle);

                      foreach (Particle2D particle2 in collidedWith)
                      {
                          newMass += particle2.mass;
                          newRadius += Math.Sqrt(particle2.radius);

                          newPosition += particle2.position;

                          newVelocity += particle2.velocity * particle2.mass;

                          particles.Remove(particle2);
                      }

                      newPosition.Divide(collidedWith.Count + 1);
                      newVelocity.Divide(newMass);

                      AddParticle(newPosition, newVelocity, newMass, newRadius);
                  }
                  #endregion
              } 
        }

最佳答案

问题是您正在使用 DateTime 来尝试测量时间的流逝。 DateTime 用于表示日期和时间,但不用于测量耗时。

使用秒表类来测量时间:

Stopwatch sw = new Stopwatch();

sw.Start();

// Do something here

sw.Stop();

Console.WriteLine(sw.ElapsedMilliseconds);
// or sw.ElapsedTicks

有关差异的更多详细信息,请查看 Eric Lippert 的博客 HERE

关于C# 增量时间实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26110228/

相关文章:

python - 对数据进行排序并应用 groupby 后查找最大时间增量

c# - 无法从 WPF 应用程序连接到 WinRT 服务器

c# - Roslyn CodeFix 找不到以前创建的 AdditionalDocument

python - python 中的 time.mktime 时区是否免费?

video - 获取 FFMPEG KeyFrames 时间或时间范围

python - 有什么办法可以在 numba 中将 timedelta64 转换为 int64 吗?

python - Python 日期和时间增量减法的惊人行为

c#,泛型类型的问题

c# - 在 C# 中的循环中捕获变量

Python Ctime 转换