本文整理匯總了TypeScript中perf_hooks.performance類的典型用法代碼示例。如果您正苦於以下問題:TypeScript performance類的具體用法?TypeScript performance怎麽用?TypeScript performance使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了performance類的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。
示例1: perfWrap
async function perfWrap(callback, args?) {
isBuildingStyles = {} // 清空
// 後期可以優化,不編譯全部
const t0 = performance.now()
await callback(args)
const t1 = performance.now()
Util.printLog(processTypeEnum.COMPILE, `編譯完成,花費${Math.round(t1 - t0)} ms`)
}
示例2: Date
await app.listen(Config.Port, Config.IP, () => {
Log.log.info(`┌`.padEnd(lineLength, '─') + `┐`);
Log.log.info(`│ Server listening: ${Config.ApiUrl}`.padEnd(lineLength, ' ') + `│`);
if (!Config.isProd()) {
Log.log.info(`│ Swagger Documentation: ${Config.ApiUrl}${Config.DocsRoute}`.padEnd(lineLength, ' ') + `│`);
Log.log.info(`│ GraphQL Playground: ${Config.ApiUrl}${Config.GraphRoute}`.padEnd(lineLength, ' ') + `│`);
}
Log.log.info(`├`.padEnd(lineLength, '─') + `┤`);
Log.log.info(`│ Memory: ${readMem()}`.padEnd(lineLength, ' ') + `│`);
Log.log.info(`│ Launch: ${new Date().toISOString()}`.padEnd(lineLength, ' ') + `│`);
Log.log.info(`│ Time to start: ${(performance.now() - startTime).toFixed(3)}ms`.padEnd(lineLength, ' ') + `│`);
Log.log.info(`│ Bootstrap time: ${(performance.now() - bootTime).toFixed(3)}ms`.padEnd(lineLength, ' ') + `│`);
Log.log.info(`└`.padEnd(lineLength, '─') + `┘`);
});
示例3: test
test('decoding and converting to RGB many frames', async (t) => {
const budget = 120000000 / cpuSpeed;
const byteStream = await readOggFile(mediumComplexOggFile);
const startTime = performance.now();
decodeAndConvertAllFrames(byteStream);
const endTime = performance.now();
const runTime = endTime - startTime;
t.true(runTime < budget, `Performance budged exceeded: ${runTime}ms (limit: ${budget})`);
if (runTime < budget) {
t.log(`Performance budget ok: ${runTime}ms (limit: ${budget})`);
}
});
示例4: build
export async function build(appPath, buildConfig: IBuildConfig) {
const {watch} = buildConfig
process.env.TARO_ENV = BUILD_TYPES.RN
fs.ensureDirSync(tempPath)
const t0 = performance.now()
await buildTemp()
const t1 = performance.now()
Util.printLog(processTypeEnum.COMPILE, `編譯完成,花費${Math.round(t1 - t0)} ms`)
if (watch) {
watchFiles()
startServerInNewWindow()
} else {
buildBundle()
}
}
示例5:
}).on("complete", () => {
const slowest = suite.filter("slowest").shift();
const fastest = suite.filter("fastest").shift();
console.log(`===\nFastest is ${fastest.name} with ~${mean(fastest)} μs/op`);
if (slowest.name !== fastest.name) {
console.log(`Slowest is ${slowest.name} with ~${mean(slowest)} μs/op`);
}
const d = ((performance.now() - _start)/1000).toFixed(2);
console.log(`Benchmark took ${d} s`);
})
示例6:
const performanceObserverCallback: PerformanceObserverCallback = (list, obs) => {
const {
duration,
entryType,
name,
startTime,
} = list.getEntries()[0];
obs.disconnect();
performance.clearFunctions();
};
示例7: async
const addMany = (names: string[]): benchmark.Suite => {
for (let name of names) {
for (let file of files) {
suite = suite.add(`${name} -> ${file}`, async () => {
let rfs = await toBench.byName(name).rfs;
rfs.require(file);
});
}
}
_start = performance.now();
return suite;
}
示例8: function
export const logRequest = function(req: express.Request, res: express.Response, next: express.NextFunction) {
const t = performance.now();
const data = Object.assign({}, req.headers);
if (req.query && Object.keys(req.query).length > 0) {
data.querystring = req.query;
}
req.logger.info(`start handling request ${ req.id }: ${ req.method } ${ req.path }`, data);
res.on("finish", () => {
req.logger.info(`finished handling request ${ req.id }`, { time: performance.now() - t });
});
next();
} as express.RequestHandler;
示例9: require
/*
----------------------
Performance monitoring instrumentation code
Will output the most expensive require resolutions to the console
Usage: set `BP_DEBUG_REQUIRE` to `true`
------------------------
*/
if (global.process.env.BP_DEBUG_REQUIRE) {
const { performance, PerformanceObserver } = require('perf_hooks')
const os = require('os')
const SAMPLING_INTERVAL = 5000
const TOP_COUNT = 10
Module.prototype.require = performance.timerify(Module.prototype.require)
require = performance.timerify(require)
let allRequires: { duration: Number; call: string }[] = []
const obs = new PerformanceObserver(list => {
const entries = list.getEntries()
entries.forEach(e => allRequires.push({ duration: e.duration, call: e[0] }))
})
obs.observe({ entryTypes: ['function'], buffered: true })
setInterval(() => {
const significantCalls = _.take(_.orderBy(allRequires, 'duration', 'desc'), TOP_COUNT)
const formattedCalls = significantCalls.map((x, i) => `${i}) ${x.duration}\t\t${x.call}`).join(os.EOL)
console.log(formattedCalls)
示例10: bootstrap
/**
* Bootstrap the application
*/
async function bootstrap() {
Log.log.debug(` * ${new Date().toISOString()}: Bootstrapping application`);
bootTime = performance.now();
const expressInstance = express();
// Configure Express Instance
expressInstance.use(helmet()); //Helmet
expressInstance.use(bodyParser.urlencoded({ extended: false }));
expressInstance.use(bodyParser.json()); //Body Parser
// Logging
const logDirectory = './log';
existsSync(logDirectory) || mkdirSync(logDirectory); // ensure log directory exists
expressInstance.use(morgan('combined', { stream: Log.stream(logDirectory) }));
morganBody(expressInstance); // Log every request body/response
// Create NestJS APP
Log.log.debug(` * ${new Date().toISOString()}: Creating NestJS app`);
const app = await NestFactory.create(AppModule, new ExpressAdapter(expressInstance), { cors: true, logger: false });
Log.log.debug(` * ${new Date().toISOString()}: Configuring NestJS app`);
app.useLogger(app.get(LogService));
// Global Route Prefix
app.setGlobalPrefix(Config.GlobalRoutePrefix);
// Do not err on fetching favicon (will only be called when surfing the api using a browser)
// which you should not do anyway. You should use a REST explorer like i.e. Postman.
app.use((req, res, next) => req.url === '/favicon.ico' ? res.status(204).send() : next());
// Pipes
app.useGlobalPipes(new ValidationPipe({ transform: true, disableErrorMessages: true }));
// Http-Exception filter
app.useGlobalFilters(new HttpExceptionFilter());
// Interceptors
// Swagger
if (!Config.isProd()) {
Log.log.debug(` * ${new Date().toISOString()}: Setting up swagger`);
const pkg = require('../package.json');
const swagger = await import('@nestjs/swagger');
const options = new swagger.DocumentBuilder()
.setBasePath(Config.GlobalRoutePrefix)
.setTitle(pkg.name)
.setDescription(pkg.description)
.setVersion(pkg.version)
.setContactEmail(pkg.author)
.addBearerAuth(Config.JwtHeaderName, 'header', 'jwt')
.build();
const document = swagger.SwaggerModule.createDocument(app, options);
swagger.SwaggerModule.setup(`/${Config.GlobalRoutePrefix}${Config.DocsRoute}`, app, document);
// Generate .json API Documentation (easly import to Restlet Studio etc...)
const apiDirectory = './api-docs';
existsSync(apiDirectory) || mkdirSync(apiDirectory); // ensure api documentation directory exists
await writeFile(`${apiDirectory}/swagger2.json`, JSON.stringify(document, null, 4), (err: NodeJS.ErrnoException) => {
if (err) throw err;
});
}
// Start listening
await app.listen(Config.Port, Config.IP, () => {
Log.log.info(`┌`.padEnd(lineLength, '─') + `┐`);
Log.log.info(`│ Server listening: ${Config.ApiUrl}`.padEnd(lineLength, ' ') + `│`);
if (!Config.isProd()) {
Log.log.info(`│ Swagger Documentation: ${Config.ApiUrl}${Config.DocsRoute}`.padEnd(lineLength, ' ') + `│`);
Log.log.info(`│ GraphQL Playground: ${Config.ApiUrl}${Config.GraphRoute}`.padEnd(lineLength, ' ') + `│`);
}
Log.log.info(`├`.padEnd(lineLength, '─') + `┤`);
Log.log.info(`│ Memory: ${readMem()}`.padEnd(lineLength, ' ') + `│`);
Log.log.info(`│ Launch: ${new Date().toISOString()}`.padEnd(lineLength, ' ') + `│`);
Log.log.info(`│ Time to start: ${(performance.now() - startTime).toFixed(3)}ms`.padEnd(lineLength, ' ') + `│`);
Log.log.info(`│ Bootstrap time: ${(performance.now() - bootTime).toFixed(3)}ms`.padEnd(lineLength, ' ') + `│`);
Log.log.info(`└`.padEnd(lineLength, '─') + `┘`);
});
}