001package net.tnemc.plugincore.core.utils; 002 003/* 004 * The New Plugin Core 005 * Copyright (C) 2022 - 2024 Daniel "creatorfromhell" Vidmar 006 * 007 * This program is free software: you can redistribute it and/or modify 008 * it under the terms of the GNU Affero General Public License as published by 009 * the Free Software Foundation, either version 3 of the License, or 010 * (at your option) any later version. 011 * 012 * This program is distributed in the hope that it will be useful, 013 * but WITHOUT ANY WARRANTY; without even the implied warranty of 014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 015 * GNU Affero General Public License for more details. 016 * 017 * You should have received a copy of the GNU Affero General Public License 018 * along with this program. If not, see <http://www.gnu.org/licenses/>. 019 */ 020 021 022import net.tnemc.plugincore.PluginCore; 023import net.tnemc.plugincore.core.compatibility.log.DebugLevel; 024 025/** 026 * Timings 027 * 028 * @author creatorfromhell 029 * @since 0.1.2.0 030 */ 031public class Timings implements AutoCloseable { 032 033 private String statement = "Timings: "; 034 private long start; 035 private long end; 036 037 /** 038 * Starts our timings in order to measure duration of methods or actions. 039 * @return The timings object. 040 */ 041 public Timings start() { 042 start = System.nanoTime(); 043 return this; 044 } 045 046 /** 047 * Used to build our timings with a statement for logging purposes. 048 * @param statement The statement to use. 049 * @return The timings instance. 050 */ 051 public Timings withStatement(String statement) { 052 this.statement = statement; 053 return this; 054 } 055 056 /** 057 * Stops the timings and returns the duration. 058 * @return Return the duration this timing lasted. 059 */ 060 public long stop() { 061 this.end = System.nanoTime(); 062 return (end - start); 063 } 064 065 /** 066 * Stops the timings and logs it to the console and server log. 067 * @param level The DebugLevel to use for this. 068 */ 069 public void stopLog(DebugLevel level) { 070 this.end = System.nanoTime(); 071 PluginCore.log().debug(statement + (end - start), level); 072 } 073 074 @Override 075 public void close() throws Exception { 076 stopLog(DebugLevel.DETAILED); 077 } 078}