Daniel Lip
Daniel Lip

Reputation: 11319

How can I calculate the time it's taking to do something inside a method?

public void SaveTest()
    {
        savingText.GetComponent<Text>().text = "Saving !";
        Save();
        savingTextLogInfo.GetComponent<Text>().text = "";
    }

I want somehow to start a timer or something before calling the Save() method and after the Save() method to assign the time it took into the savingTextLogInfo text.

and I'm calling the SaveTest in some places in the game so in each time I want it first to reset the result of time and then to calculate again the time it's taking to make the Save method.

What other logging info can I assign to the savingTextLogInfo text ? I want to try to find out why only in the build when it's saving the game freeze for a millisecond or even to a second sometimes. I don't have any errors or problems in the editor but in the build the game is freezing for a short time when saving.

This is the Save method :

public void Save()
    {
        SaveGame saveGame = new SaveGame();
        saveGame.saveObjects = new List<SaveObject>();
        for (int i = 0; i < objectsToSave.Count; i++)
        {
            SaveObject saveObject = new SaveObject();
            saveObject.transformSaver = new TransformSaver();
            Debug.Log($"{i}");
            Debug.Log($"{objectsToSave[i].name}");
            saveObject.gameObjectUniqueID = objectsToSave[i].GetComponent<GenerateGuid>().uniqueGuidID;
            var x = objectsToSave[i].GetComponents<Component>();
            var stateQueryComponent = x.Where(component => component is IStateQuery).ToList();
            List<KeyToValue> componentsState = new List<KeyToValue>();
            foreach (var z in stateQueryComponent)
            {
                var w = z as IStateQuery;
                componentsState.Add(new KeyToValue(w.UniqueId.ToString(), w.GetState()));
            }

            saveObject.transformSaver.position = objectsToSave[i].transform.position;
            saveObject.transformSaver.rotation = objectsToSave[i].transform.rotation;
            saveObject.transformSaver.scaling = objectsToSave[i].transform.localScale;

            saveObject.componentsState = componentsState;
            saveGame.saveObjects.Add(saveObject);
        }

        string json = JsonUtility.ToJson(saveGame);
        SaveSystem.Save(json);
    }

And the SaveSystem :

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public static class SaveSystem
{
    private static readonly string SAVE_FOLDER = Application.dataPath + "/save_";
    public static void Init()
    {
        if (!Directory.Exists(SAVE_FOLDER))
        {
            Directory.CreateDirectory(SAVE_FOLDER);
        }
    }

    public static void Save(string saveString)
    {
        string fileName = Path.Combine(SAVE_FOLDER, "savegame.txt");
        File.WriteAllText(fileName, saveString);

    }

    public static string Load()
    {
        string fileName = Path.Combine(SAVE_FOLDER, "savegame.txt");
        string content = File.ReadAllText(fileName);

        return content;
    }
}

Upvotes: 0

Views: 52

Answers (2)

Fabio
Fabio

Reputation: 30

Using only C#, without external references, too simple!

public static Principal() {
   DateTime StartDate = DateTime.Now;
   Secondary();
   Console.WriteLine($"{StartDate} - time elapsed in seconds: {(DateTime.Now - StartDate).TotalSeconds}");
}

public static Secondary() {
    System.Threading.Thread.Sleep(5000);
}

Upvotes: 0

Tomislav Markovski
Tomislav Markovski

Reputation: 12346

You want to use Stopwatch

var stopwatch = new Stopwatch();

stopwatch.Start();
// do some processing here

stopwatch.Stop();

Console.WriteLine($"Total time {stopwatch.ElapsedMilliseconds} ms");

You can them reset the stopwatch using stopwatch.Reset().

If you're looking to do more robust benchmarking, I would look into https://github.com/dotnet/BenchmarkDotNet This tool can run your code against different NET targets and is more flexible and configurable.

Upvotes: 5

Related Questions