fcamuso

Corso C++ 45: distruttore

Aug 6th, 2026
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.78 KB | None | 0 0
  1.  
  2. //import std;  funziona ma l'editor segnala errori inesistenti, scocciante
  3.  
  4. #include <print>
  5. #include <chrono>
  6. #include <string_view>
  7. #include <stdexcept>
  8. #include <thread>
  9.  
  10. class ExecutionTimer {
  11.     std::chrono::time_point<std::chrono::high_resolution_clock> start_time;
  12.  
  13. public:
  14.     explicit ExecutionTimer():
  15.         start_time{ std::chrono::high_resolution_clock::now() }
  16.     { }
  17.  
  18.  auto durata() {
  19.         auto end_time = std::chrono::high_resolution_clock::now();
  20.         auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
  21.  
  22.         return duration.count();
  23.     }
  24.  auto reset() {
  25.      start_time = std::chrono::high_resolution_clock::now();
  26.  }
  27.  
  28.  ~ExecutionTimer() {
  29.      auto end_time = std::chrono::high_resolution_clock::now();
  30.      auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
  31.      std::println("[Timer] Tempo trascorso: {} ms", duration.count());
  32.  }
  33.  
  34. };
  35.  
  36. void process_data(bool trigger_error) {
  37.     ExecutionTimer timer{};
  38.  
  39.     // Simulazione di un'operazione che richiede tempo
  40.     std::this_thread::sleep_for(std::chrono::milliseconds(150));
  41.  
  42.     if (trigger_error) {
  43.         throw std::runtime_error("Errore critico durante l'elaborazione");
  44.     }
  45.  
  46.     std::this_thread::sleep_for(std::chrono::milliseconds(100));
  47. }
  48.  
  49. int main() {
  50.  
  51.  
  52.     try {
  53.         std::println("--- Esecuzione con successo ---");
  54.         process_data(false);
  55.     }
  56.     catch (const std::exception& e) {
  57.         std::println("Eccezione nel main: {}", e.what());
  58.     }
  59.  
  60.     std::println("\n--- Esecuzione con errore ---");
  61.     try {
  62.         process_data(true);
  63.     }
  64.     catch (const std::exception& e) {
  65.         std::println("Eccezione nel main: {}", e.what());
  66.     }
  67.  
  68.     return 0;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment