紧急手撸 console.time()

前要
最近做需求开发想要看一下代码块的运行耗时,无意间看到了console.time()console.timeEnd(),出于好奇就深入了解了一下
原理没啥好说的,我们来看看怎么手撸一个 console.time()
最初是想着简简单单使用个 new Date() 来记录运行耗时的,谁知道后面 ...

我们来简单请出我们今天的两位主角 new Date()performance.now()new Date() 相信大家都很熟悉了,对于 performance.now() 可能比较陌生,今天就来唠唠、

new Date()

new Date() 是 JavaScript 中用于创建 Date 对象的构造函数。 Date 对象用于处理日期和时间。该函数下有很多方法,这里就细数了,各位大佬们可以自行去look look。
Date.now() 返回当前时间的时间戳(自1970年1月1日 00:00:00 UTC以来的毫秒数)。

(function () {
	// 存储计时器的对象
	const timers = {};

	// 模拟 console.time
	console.myTime = function (label) {
	  if (typeof label !== "string") {
		throw new Error("Label for console.myTime must be a string");
	  }
	  timers[label] = Date.now();
	};

	// 模拟 console.timeEnd
	console.myTimeEnd = function (label) {
	  if (typeof label !== "string") {
		throw new Error("Label for console.myTimeEnd must be a string");
	  }
	  const endTime = Date.now();
	  const startTime = timers[label];

	  if (!startTime) {
		console.warn(`No such label: ${label}`);
		return;
	  }

	  const timeDiff = endTime - startTime;
	  console.log(`${label}: ${timeDiff}ms`);
	  delete timers[label]; // 删除记录以释放内存
	};
})();

image.png
运用到实战之后发现实用性有些差,对比自带的 console.time() 精度有所欠缺,直观性比较差

new Date() 给你机会你不中用呀,弃之~✖
我们把目光放到 performance.now() 上☟

performance.now()

performance 是一个高精度的计时 API,提供了多种方法用于测量页面性能。 它是 window 对象的一部分,通常用于性能分析和优化。
performance.now() 提供比 Date.now() 更高的时间精度,通常到微秒级(千分之一毫秒),非常适合测量短时间间隔。
performance.now()new Date() 不同的是 performance.now() 的时间戳是相对的,不受系统时间更改的影响。

(function () {
	// 存储计时器的对象
	const timers = {};
	
	// 检查是否存在 performance.now() 方法
	const now =
	  typeof performance !== "undefined" && performance.now
		? performance.now.bind(performance)
		: Date.now;
	
	// 模拟 console.time
	console.myTime = function (label) {
	  if (typeof label !== "string") {
		throw new Error("Label for console.myTime must be a string");
	  }
	  timers[label] = now();
	};
	
	// 模拟 console.timeEnd
	console.myTimeEnd = function (label) {
	  if (typeof label !== "string") {
		throw new Error("Label for console.myTimeEnd must be a string");
	  }
	  const endTime = now();
	  const startTime = timers[label];
	
	  if (startTime === undefined) {
		console.warn(`No such label: ${label}`);
		return;
	  }
	
	  const timeDiff = endTime - startTime;
	  console.log(`${label}: ${timeDiff}ms`);
	  delete timers[label]; // 删除记录以释放内存
	};
})();

image.png
nice~这会看起来就具有可看性了

值得一提的是,无论是原生的 console.time() 还是手撸的 performance.now() 都会损耗 少量 性能,不宜过多使用,节制嗷~☼▲●

本篇文章的主要目的还是探究怎么去对比实现 console.time() 及其背后的代码实现原理 和了解一下 performance.now()

全剧终

感谢各位大佬查阅,跪谢~

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值